我试图将图像从右侧移动到中心,我不确定这是否是最佳方式.
var imgTag = null; var x = 0; var y = 0; var id; function doCanvas() { var canvas = document.getElementById('icanvas'); var ctx = canvas.getContext("2d"); var imgBkg = document.getElementById('imgBkg'); imgTag = document.getElementById('imgTag'); ctx.drawImage(imgBkg,0); x = canvas.width; y = 40; id = setInterval(moveImg,0.25); } function moveImg() { if(x <= 250) clearInterval(id); var canvas = document.getElementById('icanvas'); var ctx = canvas.getContext("2d"); ctx.clearRect(0,canvas.width,canvas.height); var imgBkg = document.getElementById('imgBkg'); ctx.drawImage(imgBkg,0); ctx.drawImage(imgTag,x,y); x = x - 1; }
任何建议?
解决方法
这个问题是5年之久,但由于我们现在有了requestAnimationFrame,这里有一个使用vanilla JavaScript的方法:
var imgTag = new Image(); var canvas = document.getElementById('icanvas'); var ctx = canvas.getContext("2d"); var x = canvas.width; var y = 0; imgTag.onload = animate; imgTag.src = "http://i.stack.imgur.com/Rk0DW.png"; // load image function animate() { ctx.clearRect(0,canvas.height); // clear canvas ctx.drawImage(imgTag,y); // draw image at current position x -= 4; if (x > 250) requestAnimationFrame(animate) // loop }
<canvas id="icanvas" width=640 height=180></canvas>