I am trying to create dino cloud game. but I encouter a problem .When I try to draw the image of the dinosaur in the canvas using drawImage method , the image is not drawn . Can you help me please.
const canvas = document.querySelector(".canvas");
canvas.height = 400;
canvas.width = 800;
const ctx = canvas.getContext("2d");
class Dino {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = (88 * this.height) / 94;
this.height = 70;
}
draw() {
let image = new Image();
image.src = "imgs/player/idle/dino-idle-1.png";
ctx.drawImage(image, this.x, this.y, this.width, this.height);
}}
const dino = new Dino(20, 200);
dino.draw();
I tried to draw dino using window.onload but it is not working
You need to draw an image on canvas only after the image is fully loaded (For example, using the onload trigger on the image).
Example below:
const canvas = document.querySelector(".canvas");
canvas.height = 400;
canvas.width = 800;
const ctx = canvas.getContext("2d");
class Dino {
constructor(x, y) {
this.x = x;
this.y = y;
this.height = 70;
this.width = (88 * this.height) / 94;
}
draw() {
const image = new Image();
image.onload = () => ctx.drawImage(image, this.x, this.y, this.width, this.height);
image.src = "https://www.fillmurray.com/600/400";
}}
const dino = new Dino(20, 200);
dino.draw();
<canvas class="canvas"></canvas>