我希望能够在画布上移动一些说5/6的图像。图像的位置每次都会明显改变,模拟基本动画。图像将处于定时器/延迟状态,以便它们每秒钟左右移动一次。是否有一个我可以创建的功能,以便我不必为图像反复重复相同的代码。如果图像是预先加载的,但是我不确定如何在预装图像后操作图像会很好。
如果还有一种方法可以使用requestAnimationFrame而不是setTimeout那么那就更好了。
继承我目前的代码:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded () {
images = new Array();
images[0] = "images/1.png";
images[1] = "images/2.png";
images[2] = "images/3.png";
images[3] = "images/4.png";
images[4] = "images/5.png";
imageObjs = [];
for(var i = 0; i <= 4; i++){
var imageObj = new Image();
imageObj.src = images[i];
imageObjs.push(imageObj);
}
drawFrame();
}
function drawFrame () {
setTimeout(function() {
image = new Image();
image.onload = function() {
ctx.drawImage(imageObjs[0], 0, 0);
}
image.src = "images/1.png";
}, 200);
setTimeout(function () {
image2 = new Image();
image2.onload = function() {
ctx.drawImage(imageObjs[1], 200, 0);
};
image2.src = "images/2.png";
}, 1000);
}
答案 0 :(得分:0)
您表示有兴趣让代码执行以下操作:
以下是示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var images=[];
images.push({x:20,y:200,moveX:5,maxX:250,delay:100,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/cars1.png'});
images.push({x:20,y:30,moveX:10,maxX:100,delay:500,nextTime:0,url:'https://dl.dropboxusercontent.com/u/139992952/multple/sun.png'});
var imageCount=images.length;
for(var n=0;n<images.length;n++){
var i=images[n];
i.img=new Image();
i.img.onload=start;
i.img.src=i.url;
}
function start(){
if(--imageCount>0){return;}
requestAnimationFrame(animate);
}
function animate(time){
requestAnimationFrame(animate);
var needsRedrawing=false;
for(var n=0;n<images.length;n++){
var i=images[n];
if(time>i.nextTime){
if(i.x+i.moveX<i.maxX){
i.x+=i.moveX;
i.nextTime+=i.delay;
needsRedrawing=true;
}
}
}
if(needsRedrawing){
ctx.clearRect(0,0,cw,ch);
for(var n=0;n<images.length;n++){
var i=images[n];
ctx.drawImage(i.img,i.x,i.y);
}
}
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>