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. Every Frame canvas creates a new triangle but I just want that canvas animate one triangle.

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

Answers


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. 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
                ;

Need Your Help

Dynamically add and remove content in GUI form

arrays wpf winforms powershell

I am trying to create in PowerShell a GUI window with dynamic content. I need to: