Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created June 18, 2021 13:27
Show Gist options
  • Save rajivnarayana/a2c4ae4d65aa73b13979381ba5041524 to your computer and use it in GitHub Desktop.
Save rajivnarayana/a2c4ae4d65aa73b13979381ba5041524 to your computer and use it in GitHub Desktop.
Hero Animation on a canvas.
<canvas id="canvas" width="400" height="600"></canvas>
<script src="./game.js"></script>-
const canvasId = "canvas"
document.addEventListener("DOMContentLoaded", () => {
const canvas = document.getElementById(canvasId);
const ctx = canvas.getContext('2d');
const heroPosition = {
x : 10,
y : 15
}
/**
*
* @param {CanvasRenderingContext2D} ctx
*/
const noOfRows = 600 / 20;
const noOfColumns = 400 / 20;
function drawBackground(ctx) {
const { width, height } =canvas.getBoundingClientRect();
//Draw border
ctx.strokeStyle = "lightgray";
ctx.rect(0, 0, width, height);
ctx.stroke();
ctx.lineWidth = 0.5;
// ctx.moveTo(0, 0);
// ctx.lineTo(200, 300);
// ctx.stroke();
//Draw rows
for (let i=0; i < noOfRows; i++) {
ctx.moveTo(0, i * 20);
ctx.lineTo(400, i * 20);
}
//Draw cols
for (let i=0; i < noOfColumns; i++) {
ctx.moveTo(i * 20, 0);
ctx.lineTo(i * 20, 600);
}
ctx.stroke();
}
/**
*
* @param {CanvasRenderingContext2D} ctx
*/
function drawHero(ctx) {
ctx.fillStyle = "red"
console.log(heroPosition.x * 20 , heroPosition.y * 20);
ctx.fillRect(heroPosition.x * 20, heroPosition.y * 20, 20, 20);
}
/**
*
* @param {CanvasRenderingContext2D} ctx
*/
function drawWorld(ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBackground(ctx);
drawHero(ctx);
}
let lastAnimationTime;
const step = (time) => {
if (!lastAnimationTime) {
lastAnimationTime = time;
} else if (time - lastAnimationTime > 100) {
lastAnimationTime = time;
heroPosition.y++;
if (heroPosition.y > 29) {
heroPosition.y = 0;
}
}
drawWorld(ctx);
window.requestAnimationFrame(step);
};
window.requestAnimationFrame(step);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment