user1469270
user1469270

Reputation:

Moving an element on the HTML canvas

I have drawn a rectangle on the canvas and I just want it to move every half a second. I'm trying to increase the y coordinate every 0.5 seconds -- but nothing is happening.

Could anyone tell me where I'm going wrong?

JSFIDDLE

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas); 

setInterval(function(){
var x = 100;
var y= 300;
var block = ctx.fillRect(x, y, 100, 120);
y++;


},500);

Upvotes: 0

Views: 110

Answers (3)

user1693593
user1693593

Reputation:

You are resetting your x and y for each call so they never increase. Also, you need to clear previous drawn rectangle or they will becomes smeared.

To be able to cancel the loop later you can consider storing the timer id returned from setInterval so you can call clearInterval(id) when needed (ie. at a condition).

var x = 100;
var y = 300;
var tid;

tid = setInterval(function(){
    ctx.clearRect(x - 2, y - 2, 104, 124); /// compensate for anti-aliasing
    ctx.fillRect(x, y, 100, 120);
    y++;
},500);

A condition could be:

if (y > canvas.height) clearInterval(tid);

Upvotes: 1

paskl
paskl

Reputation: 611

You are setting x and y always to the default values when the function gets executed. You should outsource them.

var canvas = document.createElement("canvas");
var c = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 480;
document.body.appendChild(canvas);


var x = 100;
var y = 300;
setInterval(function(){    
    c.beginPath();
    c.arc(x, y, 100, 120, Math.PI * 2, false);
    c.fill();
    x += 10;


},500);

See this fiddle.

Upvotes: 0

tckmn
tckmn

Reputation: 59363

Move

var x = 100;
var y = 300;

Out of the function within setInterval, so that they don't get reset every frame.

Upvotes: 1

Related Questions