About
Explore
Events & Classes
Support Us
Join
Sign In
Coding with Rumaysa
View Project Page
Run
Fullscreen
Run Around || with Princess Leia!
HTML
CSS
JS
<!-- Created by Coding with Rumaysa, subject to copyright. FULLSCREEN HIGHLY RECOMMENDED. ARROW KEYS FOR NAV. --> <!DOCTYPE HTML> <html> <head> <title>Page Title</title> <meta charset="utf-8"> <meta name="author" content="Coding with Rumaysa"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <canvas id="canvas1"></canvas> </body> </html>
#canvas1 { width: 800px; height: 500px; border: 1px solid black; background-color: #d79c50; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
const canvas = document.getElementById("canvas1"); const ctx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 500; const keys = []; const player = { x: 200, y: 300, width: 32, height: 48, frameX: 0, frameY: 0, speed: 9, moving: false } const playerSprite = new Image(); playerSprite.src = "https://justcodaborate.org/project_assets/princessleia.png"; const background = new Image(); background.src = "https://justcodaborate.org/project_assets/sand.jpg"; function drawSprite(img,sX,sY,sW,sH,dX,dY,dW,dH) { ctx.drawImage(img,sX,sY,sW,sH,dX,dY,dW,dH); } window.addEventListener("keydown", function(e){ keys[e.keyCode] = true; player.moving = true; }); window.addEventListener("keyup", function(e){ delete keys[e.keyCode]; player.moving = false; }); function movePlayer() { if(keys[38] && player.y > 0) { player.y -= player.speed; player.frameY = 3; player.moving = true; } if(keys[37] && player.x > 0) { player.x -= player.speed; player.frameY = 1; player.moving = true; } if(keys[40] && player.y < canvas.height - player.height) { player.y += player.speed; player.frameY = 0; player.moving = true; } if(keys[39] && player.x < canvas.width - player.width) { player.x += player.speed; player.frameY = 2; player.moving = true; } } function handlePlayerFrame() { if(player.frameX < 3 && player.moving) player.frameX++; else player.frameX = 0; } /* function animate() { ctx.drawImage(background,0,0,canvas.width,canvas.height); drawSprite(playerSprite,player.width * player.frameX,player.height * player.frameY,player.width,player.height,player.x,player.y,player.width,player.height); movePlayer(); handlePlayerFrame(); requestAnimationFrame(animate); } animate(); */ let fps, fpsInterval, startTime, now, then, elapsed; function startAnimating(fps) { fpsInterval = 1000/fps; then = Date.now(); startTime = then; animate(); } function animate() { requestAnimationFrame(animate); now = Date.now(); elapsed = now - then; if(elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); } ctx.drawImage(background,0,0,canvas.width,canvas.height); drawSprite(playerSprite,player.width * player.frameX,player.height * player.frameY,player.width,player.height,player.x,player.y,player.width,player.height); movePlayer(); handlePlayerFrame(); } startAnimating(500);