Canvas is an HTML5 element which is used to draw graphics using a script. It is only a container for graphics and has several methods for drawing boxes, texts, images etc. We can easily design a line, an arc, a circle and much more. The canvas element has getContext method which is used to attain the drawing features. It also takes one parameter of the form of context 2D.
In this blog, I will share easy ways to make a spin loader using canvas.
Loader has it’s own advantages. It is extensively used to pre-process the file. For example, if the user clicks an application or a file to open it. He is will be shown a loader indicating the ‘file is opening’. This will further inhibit the user to refrain from making continuous clicks.
Below is the code to design loader:-
HTML-
<canvas id="loader" width="100" height="100"></canvas>
CSS-
#loader{border-radius: 50%;border:1px dashed #CCC;}
JQUERY-
var context = document.getElementById('loader').getContext('2d'); //draw circle with 2D surface
var l = 0; //it is the initial value of loader
var init = 4.72; //starting position from where loader will be started
var cw = context.canvas.width; //width of the loader
var ch = context.canvas.height; //height of the loader
var diff; //it will be used to calculate the difference between amount loaded and remained
function loadersimulate(){
diff = ((l / 100) * Math.PI*2*10).toFixed(2); //fixed is used to fix variable to avoid decimal places
context.clearRect(0, 0, cw, ch); //clears the specified pixels of rectangle.
context.lineWidth = 10; //progress bar width
context.fillStyle = '#C43B1E'; // color of percentage text
context.strokeStyle = "#C43B1E"; // color of progress bar
context.textAlign = 'center';// to align text in center
context.fillText(l+'%', cw*.5, ch*.5+2, cw); //show the percentage
context.beginPath(); //begins the path
context.arc(50, 50, 50, init, diff/10+init, false); //create arc or circle
context.stroke();
if(l >= 100){ //check if the value of l is greater than or equal to 100
clearTimeout(a); //animation will be stopped
}
l++; //here the value of loader will be increased by 1
}
var a = setInterval(loadersimulate, 50); // evaluates the expression after every 50 millisecond untill cleartimeout will be found
HERE IS THE FIDDLE LINK:-
Hope you like the blog post. Please share your comments/brickbats in the comment section below.
0 Comment(s)