0

As the title says. I draw the image with canvas (1376x1440) but when I open the website for the first time everything is black until refresh then it works and draws it fine.

I host website via express with node.js.

Code where I import the image

var city_Image = new Image();  
city_Image.src = '/Pictures/city.png' 

var city = map(city_Image.width*2,city_Image.height*2,city_Image,"city",changeTo2DMapArray(city_Array1D,city_Image))

And where I draw it

var map = (maxX,maxY,image,name,grid) => {
var self = {
    name:name,
    minX:0,
    minY:0,
    maxX:maxX,
    maxY:maxY,
    image:image,
    grid:grid
}


self.drawMap = function(canvas,ctx){
    ctx.drawImage(self.image,(canvas.width-self.maxX),(canvas.height-self.maxY),self.maxX,self.maxY)  
}
return self;
}

Does any one have any ideas?

EDIT: I also have "camera" function which i don't understand perfectly

function draw(ctx,canvas,player,world) {
    ctx.setTransform(1,0,0,1,0,0);//reset the transform matrix as it is cumulative
    ctx.clearRect(0, 0, canvas.width, canvas.height);//clear the viewport AFTER the matrix is reset

    //Clamp the camera position to the world bounds while centering the camera around the player                                             
    var camX = clamp(-player.x + canvas.width/2, world.minX,  world.maxX - canvas.width );
    var camY = clamp(-player.y + canvas.height/2, world.minY,  world.maxY - canvas.height);

    ctx.translate( camX, camY );    

    //Draw everything       
    world.drawMap(canvas,ctx)  
    ctx.drawImage(player.sprite,player.x,player.y,64,64)
}

function clamp(value, min, max){
    if(value < min) return min;
    else if(value > max) return max;
    return value;
}

Maybe this has to do something with it?

Merci
  • 3
  • 2
  • This could relate to how you're declaring your `ctx` drawing context. – tadman Mar 12 '18 at 20:01
  • Images do not load instantaneously. Setting the "src" attribute will begin an HTTP network request, but until the image is received by the browser you won't be able to use it. – Pointy Mar 12 '18 at 20:01
  • @Pointy how could I fix it? does it have to do something with preloading? – Merci Mar 12 '18 at 20:30

1 Answers1

1

You should use an onload event:

city_Image.onload = function(map(...));

Thevs
  • 3,189
  • 2
  • 20
  • 32