2016-04-29 44 views
0

我知道你可以使用ctx.translate()來翻譯圖像,但是當我這樣做時,它不起作用。我不知道什麼是錯的。我花了2個小時努力弄清楚。這裏是我的代碼:爲什麼我不能翻譯JS畫布圖像?

<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); 
} 
+0

我認爲你需要重新繪製圖像後翻譯。添加'ctx.drawImage(img,0,0);'在你的onkeydown函數中加入 – Matt

回答

0

您需要翻譯後重繪您的圖像,添加以下內容:

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

想法

var counter=0; 

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

現在可以翻譯了。但是,每按一次按鍵,它就會循環移動圖像100個像素。我只想讓它移動到那些座標一次。 – Critical

+0

我只能建議添加一個計數器/布爾值和一個如果在函數內只能移動如果假或計數器= 0 – Matt

+0

@Critical查看我的更新 – Matt

相關問題