Skip to content

Instantly share code, notes, and snippets.

@marcusshepp
Last active October 2, 2024 10:40
Show Gist options
  • Save marcusshepp/a9a857f78f58ea42c9c5bdf5ab84c96b to your computer and use it in GitHub Desktop.
Save marcusshepp/a9a857f78f58ea42c9c5bdf5ab84c96b to your computer and use it in GitHub Desktop.
Load an img with html canvas
let cat;
let loadCat = () => {
let img = new Image();
img.style.width = '100px';
img.style.height = '100px';
img.addEventListener('load', () => {
cat = img;
});
img.src = 'cat.jpg';
document.getElementsByTagName('body')[0].appendChild(img);
img.style.display = 'none';
};
window.addEventListener('load', loadCat);
function gameLoop() {
if (this.paused) {
ctx.fillText('Cat', 10, 20);
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (cat) {
ctx.drawImage(cat, pos.x, pos.y, snake.width, snake.height);
}
requestAnimationFrame(gameLoop);
}
gameLoop();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment