codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › JS graphics

JS graphics

Animate on a canvas.

Use requestAnimationFrame to redraw each frame and move shapes a little each time.

Example code

<canvas id='c' width='280' height='100' style='border:1px solid #888'></canvas>
<script>
const g=c.getContext('2d');let x=0;
function f(){g.clearRect(0,0,280,100);g.fillStyle='tomato';g.beginPath();g.arc(x,50,16,0,7);g.fill();x=(x+2)%280;requestAnimationFrame(f);}
f();
</script>

Run this code in the online editor

← JS typed arraysJS AJAX →