canvas入门基础(九):基础动画
//动画循环 if (!window.requestAnimationFrame) { window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (callback) { return window.setTimeout(callback, 17 ); }); }
if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = (window.cancelRequestAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame || window.clearTimeout); }
var cc = document.getElementById("canvas");
var cxt = cc.getContext("2d");
var ca = document.createElement("canvas");
ca.width=500;
ca.height=500;
var cxt2 = ca.getContext("2d");
var x = y = 0;
//加载多个图片
function loadImages(sources, callback) {
var count = 0,
images = {},
imgNum = 0;
for (k in sources) {
imgNum++;
}
for (k in sources) {
images[k] = new Image();
images[k].onload = function() {
if (++count >= imgNum) {
callback(images);
}
}
images[k].src = sources[k];
}
}
var sources = [];
function drawGameImage() {
sources = ["gameimage/0.png", "gameimage/1.png", "gameimage/2.png", "gameimage/3.png", "gameimage/4.png", "gameimage/5.png", "gameimage/6.png", "gameimage/7.png", "gameimage/8.png", "gameimage/2.png", "gameimage/3.png", "gameimage/4.png", "gameimage/5.png", "gameimage/6.png", "gameimage/9.png", "gameimage/10.png"]; //调用图片预加载函数,实现回调函数
loadImages(sources, function(images) {
var x = y = 0;
for (var i = 0; i < sources.length; i++) {
cxt2.drawImage(images[i], x * 100, y * 100, 100, 100);
if (i < 4) {
x++;
} else if (i >= 4 && i < 8) {
y++;
} else if (i >= 8 && i < 12) {
x--;
} else {
y--;
}
}
});
}
drawGameImage();
var times = Math.floor(Math.random() * 10) + sources.length * 2;
var v = 0;
function move() {
var moveX = 400;
var speed = 100;
if (x < moveX && y == 0) {
x += speed;
} else if (x == moveX && y < moveX) {
y += speed;
} else if (y == moveX && x > 0) {
x -= speed;
} else if (x == 0 && y > 0) {
y -= speed;
}
cxt.clearRect(0, 0, 500, 500);
cxt.drawImage(ca,0,0,500,500);
cxt.fillStyle = "rgba(0,0,0,.5)";
cxt.fillRect(x, y, 100, 100);
if (v > times) {
cancelAnimationFrame();
}
v++;
requestAnimationFrame(move);
}
move();
function loadImages(sources, callback) { var count = 0, images = {}, imgNum = 0; for (k in sources) { imgNum++; } for (k in sources) { images[k] = new Image(); images[k].onload = function() { if (++count >= imgNum) { callback(images); } } images[k].src = sources[k]; } }
- 在loadImages方法中,我们应该先绑定image.onload事件,后加载图片
- for...in循环 与 for循环的区别
var ca = document.createElement("canvas"); ca.width=500; ca.height=500; var cxt2 = ca.getContext("2d");
drawGameImage();