Thursday, April 13, 2017

Running around in circle animation using HTML5 Canvas

Using HTML5 and JavaScript, I'll be creating a running around in circle animation effect. The screen shots below will show how the animation will look like:


The animation will consist mainly of drawing a portion on the circle at regular intervals. Each interval will clear the previously drawn portion and start the new portion where the cleared portion ended.

The HTML code creates a canvas with an id "myCanvas" width of 600px and height of 400px. As soon as all HTML elements are rendered, the JavaScript function init() is called.

The CSS code creates a black solid border around the canvas.
The JavaScript starts by declaring variables that will be used for the animation. The variable c will hold the canvas object while ctx will define the context of the canvas. The variable arcLength will be the portion of the circle that will be drawn, which is 1/16 of the circumference. The variable startLength will be set to initial zero. In HTML5, the value zero is positioned at the 3 o'çlock of the circle. The endAngle is end portion to be drawn.
The function init() is called when all HTML elements have been rendered. The document object function querySelector() identifies the canvas by its id and assigns it as an object to the variable c. The context of the canvas will be in 2D. The portion that will be drawn on the circle to create the animating effect will be in color red. The function draw() is called next.
The setInterval function called by draw() is a built in JavaScript function. This takes two parameters, a callback function, and the interval in milliseconds when the callback function will be called repeatedly.
The callback starts by refilling the canvas with the color yellow. The circle portion that was drawn in the previous call is covered by the refill of the canvas, i.e. cleared on the current call. HTML5 defines zero position at 3 o'clock of the circle; the position 2 closes the circle. When the endAngle reaches the position 2, both startAngle and endAngle are reset.  Otherwise, the startAngle takes the previous endAngle and the endAngle is incremented by the circle portion to be drawn.

The circle, or circle portion is drawn on the canvas.
The jsfiddle link to the full code is at https://jsfiddle.net/jundolor/bebyqpxq/

This is my  first attempt in creating animations using HTML5. In future blogs, I will attempt to create more complex animations.

No comments:

Post a Comment