How shapes images REALLY move on the Canvas
suggest changeA 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…
- …where you drew the circle (it does not know x,y =[20,30]).
- …the size of the circle (it does not know radius=15).
- …the color of the circle. (it does not know the circle is blue).
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.
- Canvas can’t move the circle or resize the circle.
- Canvas can’t recolor the circle or erase the circle.
- Canvas can’t say if the mouse is hovering over the circle.
- Canvas can’t say if the circle is colliding with another circle.
- Canvas can’t let a user drag the circle around the Canvas.
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.
- Erase the canvas
- Update the circle’s position
- Redraw the circle in it’s new position
- Repeat, repeat, repeat …
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);
}