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

123
Views
No image width, canvas / constructor javascript

Hello everyone this is my problem :

I am currently creating a game following a tutorial, but I have a problem in my constructor.

I'm using a constructor to draw some platform. I'm trying to draw an image on my platform but it doesnt work.

The image appears but not its width (things I need to have to make the project works correctly). But after a reload, the width is correct, and the project is working.

So I assume that I have to declare my image somewhere (maybe with an onload) but I tried a lot of things without it ever working.

Here is my code :

class Platform {  
  constructor({x, y, image}) {
    this.position = {
      x: x,
      y: y
    }
    
    this.image = image
    this.width = image.width
    this.height = image.height

  }

  draw() {
    canvas.drawImage(this.image, this.position.x, this.position.y)
  }
}

const image = new Image()
image.src = platform

console.log(image)
console.log(image.width)

const player = new Player()
const platforms = [new Platform({
  x: 200,
  y: 100,
  image: image
}), new Platform({
  x: 500, y: 200, image: image})]

const keys = {
  right: {
    pressed: false
  },
  left: {
    pressed: false
  }
}


let scrollOffset = 0


function animate() {
  requestAnimationFrame(animate)
  canvas.clearRect(0, 0, getCanvas.width, getCanvas.height)
  platforms.forEach((platform) => {
    platform.draw()
  })

So as you can see, on the first load, I have no width : 0 width

But, if I hits reload, there it is : 580 width

Im someone had an idea for me...

Thanks in advance and sorry for my english

about 4 years ago · Juan Pablo Isaza
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!