javascript - 如何用一个移动的三 Angular 形/矩形创建 Canvas 动画?

标签 javascript html animation canvas frame

问题是,动画每帧都会创建一个三 Angular 形。但我想要的是,只有一个三 Angular 形会移动/被动画化。我该如何解决? 此时, Canvas 在随机的 X 和 Y 位置上绘制一个三 Angular 形,然后向左移动,然后向右移动,依此类推。每个帧 Canvas 都会创建一个新的三 Angular 形,但我只想让该 Canvas 为一个三 Angular 形添加动画。

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

最佳答案

您还需要清除每个帧的 Canvas :

function draw() {  
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    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();
}

PS:你的动画循环中不需要那个polyfill,它只会消耗不必要的循环。把它放在脚本的开头就可以了,而且你还缺少无前缀的版本:

reqAnimFrame =  window.requestAnimationFrame ||  /// you will need this too..
                window.mozRequestAnimationFrame    ||
                window.webkitRequestAnimationFrame ||
                window.msRequestAnimationFrame     ||
                window.oRequestAnimationFrame
                ;

关于javascript - 如何用一个移动的三 Angular 形/矩形创建 Canvas 动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20567342/

相关文章:

html - 表头没有收到 CSS(我认为)

javascript - 如果子项在垂直列表中处于事件状态,则保持导航菜单打开

python - 无法在 matplotlib : Windows permission denied 中保存动画

javascript - 如何在石灰调查验证中禁用 JavaScript 警报

javascript - 在另一个 js 文件中调用 JavaScript 函数

JavaScript 弹出窗口在 PHP IF 函数中显示,无需 onClick

javascript - 为其他幻灯片保留初始动画

Android-如何在矢量图上实现中心比例动画

javascript - 如何从数组中删除元素?

javascript - 使用 HTML 和 JavaScript,如何存储用户的选择并将这些值作为输入参数传递?