【问题标题】:How to create a canvas animation with one moving triangle/rectangle?如何使用一个移动的三角形/矩形创建画布动画?
【发布时间】: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


    【解决方案1】:

    您还需要清除每一帧的画布:

    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
                    ;
    

    【讨论】:

    • 那个很难!! :-)
    • @GameAlchemist 对于刚接触它的人不知道它肯定会..随时upvote :)
    猜你喜欢
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    相关资源
    最近更新 更多