How shapes images REALLY move on the Canvas

suggest change

A problem: Canvas only remembers pixels, not shapes or images

This is an image of a circular beach ball, and of course, you can’t drag the ball around the image.

It may surprise you that just like an image, if you draw a circle on a Canvas you cannot drag that circle around the canvas. That’s because the canvas won’t remember where it drew the circle.

// this arc (==circle) is not draggable!!
context.beginPath();
context.arc(20, 30, 15, 0, Math.PI*2);
context.fillStyle='blue';
context.fill();

What the Canvas DOESN’T know…

What the Canvas DOES know…

Canvas knows the color of every pixel on it’s drawing surface.

The canvas can tell you that at x,y==[20,30] there is a blue pixel, but it does not know if this blue pixel is part of a circle.

What this means…

This means everything drawn on the Canvas is permanent: immovable and unchangeable.

But Canvas can give the I-L-L-U-S-I-O-N of movement

Canvas can give the illusion of movement by continuously erasing the circle and redrawing it in a different position. By redrawing the Canvas many times per second, the eye is fooled into seeing the circle move across the Canvas.

This code gives the illusion of movement by continuously redrawing a circle in new positions.

// create a canvas
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");
ctx.fillStyle='red';
document.body.appendChild(canvas);

// a variable indicating a circle's X position
var circleX=20;

// start animating the circle across the canvas
// by continuously erasing & redrawing the circle
// in new positions
requestAnimationFrame(animate);

function animate(){
    // update the X position of the circle
    circleX++;      
    // redraw the circle in it's new position
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.arc( circleX, 30,15,0,Math.PI*2 );
    ctx.fill();
    // request another animate() loop
    requestAnimationFrame(animate);
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents