JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
cubes = [];
//random int
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function draw() {
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, w, h);
var t = new Date().getTime();
cubes.forEach(function(cube) {
var speed = cube.speed || 500;
cube.dx = 50 * Math.sin(t / speed - cube.offset);
cube.dy = 200 * Math.sin(t / speed);
drawCube(ctx, cube);
});
window.requestAnimationFrame(draw);
}
function drawCube(ctx, cube) {
ctx.fillStyle = cube.color;
ctx.fillRect(cube.x + cube.dx, cube.y + cube.dy,
cube.w, cube.h);
}
function init() {
canvas = document.getElementById('canvas');
w = canvas.width;
h = canvas.height;
var i = 0;
while (i < 100) {
cubes.push({
color: "#" + rand(0, 999999),
w: rand(50, 150),
h: rand(50, 150),
x: rand(0, w),
y: rand(0, h),
dx: 0,
dy: 0,
offset: rand(0, 10),
speed: rand(500, 2000)
});
i++;
}
window.requestAnimationFrame(draw);
}
init();