【发布时间】:2014-01-01 06:30:52
【问题描述】:
问题是,动画每帧都会创建一个三角形。但我想要,只有一个三角形移动/动画。我该如何解决? 此刻画布在随机的 X 和 Y 位置上绘制一个三角形,然后向左移动,然后向右移动,依此类推。每个 Frame 画布都会创建一个新三角形,但我只希望该画布为一个三角形设置动画。
window.onload = function () {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var W = canvas.width = window.innerWidth;
var H = canvas.height = window.innerHeight;
var x = Math.floor(Math.random()*W);
var y = Math.floor(Math.random()*H);
var speed = 20;
function animate() {
reqAnimFrame = window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame
;
reqAnimFrame(animate);
x += speed;
if(x <= 0 || x >= W - 300){
speed = -speed;
}
draw();
}
function draw() {
ctx.beginPath();
ctx.fillStyle = "rgba(0,204,142,0.5)";
ctx.moveTo(x,y);
ctx.lineTo(x + 150, y + (-180));
ctx.lineTo(x + 300, y);
ctx.scale(1,1);
ctx.rotate(Math.PI / 1);
ctx.fill();
}
animate();
};//onload function
【问题讨论】:
标签: javascript html animation canvas frame