Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
I Can't draw an image using drawImage method in html5 canvas

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!