HTML5 canvas draw animated circle


HTML:

<canvas id="myCanvas" width="600" height="200"></canvas>

CSS:

body {
    margin: 0px;
    padding: 0px;
}

Javascript:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var myCircle = {
    x: 20,
    y: canvas.height / 2,
    radius: 20,
    color: "red",
    borderwidth: 1,
    bordercolor: '#003300'
};

function draw(  ){
    //speed: pixels per second
    Speed = 60; 
    myCircle.x += Speed/60 ;
    context.clearRect(0,0,canvas.width,canvas.height);
    context.beginPath();
    context.arc(myCircle.x, myCircle.y, myCircle.radius, 0, 2 * Math.PI, false);
    context.fillStyle = myCircle.color;
    context.fill();  
    context.lineWidth = myCircle.borderwidth;
    context.strokeStyle = myCircle.bordercolor;
    context.stroke();
}
 
setInterval(draw ,1000/60)

Result:

Try it yourself:
https://jsfiddle.net/gLx1a21f/

We can use the script below to do the same:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var myCircle = {
    x: 20,
    y: canvas.height / 2,
    radius: 20,
    color: "red",
    borderwidth: 1,
    bordercolor: '#003300'
};
var timestart = (new Date()).getTime();

function draw(timestart){
    //speed: pixels per second
    Speed = 60; 
    var deltatime = (new Date()).getTime();
    deltatime = deltatime - timestart;
    myCircle.x += Speed * deltatime / 1000 ;
    context.clearRect(0,0,canvas.width,canvas.height);
    context.beginPath();
    context.arc(myCircle.x, myCircle.y, myCircle.radius, 0, 2 * Math.PI, false);
    context.fillStyle = myCircle.color;
    context.fill();  
    context.lineWidth = myCircle.borderwidth;
    context.strokeStyle = myCircle.bordercolor;
    context.stroke();
}
 
setInterval(function(){
    draw(timestart)
    timestart = (new Date()).getTime();
} ,1000/60)

Try it yourself:
https://jsfiddle.net/8p5vtqg9/

Related Post

,

Trackbacks/Pingbacks

  1. HTML5 canvas: Draw a circle move any direction | Free Online Tutorials - August 28, 2015

    […] Read first: HTML5 canvas draw animated circle […]

Leave a Reply