Critical Critical - 7 months ago 28
Javascript Question

Why Can't I Translate JS Canvas Image?

I know you can translate images using

ctx.translate()
but when I do it, it doesn't work. I don't know what is wrong. I spent a solid 2 hours trying to figure it out. Here is my code:

<canvas id="tank_layer" height="1080" width="1920"></canvas>

var canvas = document.getElementById('tank_layer'),
ctx = canvas.getContext('2d')

document.onkeydown=function(){

ctx.translate(100,150)
}
img = new Image(1920, 1080),
img.src="../tanks/maps/2.png"

img.onload = function() {
ctx.drawImage(img, 0, 0);
}

Answer

You need to redraw your image after translation so add the following:

document.onkeydown=function(){ 
    ctx.translate(100,150) 
    ctx.drawImage(img,0,0)
}

idea

var counter=0;

document.onkeydown=function(){ 
    if (counter===0) {
        ctx.translate(100,150);
        ctx.drawImage(img,0,0);
        counter++;
    }
}