我有动画矩形jsFiddle Demo
如何减慢动画并使其更稳定?
我尝试使用循环延迟,但延迟循环和 requestAnimationFrame 之间存在冲突
我不想更改参数window.setTimeout(f, 1e3 / 60);
因为有更多的代码块需要良好的偏好。
非常感谢。
循环延迟:
for (i = 0; i < 10; i++) {
(function (i) {
window.setTimeout(function () {}, i * 2000);
}(i));
}
我的代码:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var my_gradient = ctx.createLinearGradient(0, 0, 0, 300);
window.requestAnimationFrame = function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
window.cancelAnimationFrame = function() {
return window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.msCancelAnimationFrame ||
window.oCancelAnimationFrame ||
function(f) {
window.setTimeout(f,1e3/60);
}
}();
var randompos = {};
RandomPosition();
function DrawBackround() {
ctx.globalAlpha = 1;
ctx.clearRect(0, 0, 200, 200);
my_gradient.addColorStop(0, '#002EB8');
my_gradient.addColorStop(1, '#4D6DCD');
ctx.fillStyle = my_gradient;
ctx.fillRect(0, 0, 200, 200);
}
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
function RandomPosition() {
DrawBackround();
ctx.globalAlpha = 0.5;
var dt = 10;
for (i = 0; i < 3; i++) {
n = Math.floor(Math.random() * 8) + 1;
switch (n) {
case 1:
randompos.x = 0;
randompos.y = dt; //12
break;
case 2:
randompos.x = dt;
randompos.y = dt; //1
break;
case 3:
randompos.x = dt;
randompos.y = 0; //3
break;
case 4:
randompos.x = dt;
randompos.y = -dt; //4
break;
case 5:
randompos.x = 0;
randompos.y = -dt; //6
break;
case 6:
randompos.x = -dt;
randompos.y = -dt;
break;
case 7:
randompos.x = -dt;
randompos.y = 0;
break;
case 8:
randompos.x = -dt;
randompos.y = dt;
break;
default:
}
ctx.fillStyle = get_random_color();
ctx.fillRect(randompos.x + 50, randompos.y + 50, 100, 100);
}
window.requestAnimationFrame(RandomPosition);
for (i = 0; i < 10; i++) {
(function (i) {
window.setTimeout(function () {}, i * 2000);
}(i));
}
}