简体   繁体   English

如何创建具有一个移动三角形/矩形的画布动画?

[英]How to create a canvas animation with one moving triangle/rectangle?

The Problem is, that the animation creates a triangle every frame. 问题是,动画每帧都会创建一个三角形。 But I want, that just one triangle moves / be animated. 但我想,只有一个三角形移动/动画。 How do I fix this? 我该如何解决? In the moment canvas draw a triangle on a random X and Y Position and moves to the left and after that to the right and so on. 此时,画布在随机的X和Y位置上绘制一个三角形,然后向左移动,然后向右移动,依此类推。 Every Frame canvas creates a new triangle but I just want that canvas animate one triangle. 每个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

You need to clear the canvas for each frame as well: 您还需要清除每一帧的画布:

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: You don't need that polyfill inside your animation loop, it will only eat unnecessary cycles. PS:您不需要在动画循环中使用该polyfill,它只会吃掉不必要的循环。 Put it in the beginning of the script and you'll be good, and you are also missing unprefixed version: 将其放在脚本的开头,您会感觉很好,并且还缺少未前缀的版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM