Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting animation with html5 canvas

I am trying to implement a wating animation of the kind mentioned in this question, particularly something that looks like this:

enter image description here

But I do not want to use graphic files, and am trying to implement it purely in html5 canvas and javascript. Also, I want a circular black background rather than a square one. As a first step, I tried to draw a static frame (without any movement/rotation) and did this:

<html>
<head><script>
window.onload = function(){
    var c=document.getElementById("waiting").getContext("2d");
    c.lineCap="round";
    c.fillStyle="#353535";
    c.translate(100,100);
    function slit(p){
        shade = 256*p;
        th = 2*Math.PI*p;
        cos = Math.cos(th);
        sin = Math.sin(th);
        c.strokeStyle = '#'+((shade<<16)+(shade<<8)+shade).toString(16);
        c.moveTo(55*cos, 55*sin);
        c.lineTo(84*cos, 84*sin);
        c.stroke();
        c.closePath();
    }
    c.lineWidth=0;
    c.arc(0,0,100,0,Math.PI*2);
    c.fill();
    c.lineWidth=7;
    for(var i = 0;i<1;i+=0.05){slit(i);}
}
</script></head>
<body><canvas id="waiting" width=200 height=200></canvas></body>
</html>

The result I get is:

enter image description here

The problem is that, the lineCap="round" is not working correctly for all of the "slits", and the lineWidth=0 attribute is not working for the edge of the circle. What am I doing wrong? I checked it with Chrome 16.0.912.63 and Firefox 10.0, and got similar results.


For the next step, I am going to let parts of the functions that I created above interact with

window.animationFrames = (function(callback){
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback){window.setTimeout(callback, 1000 / 60);};
 })();

but for the time being, I need to solve this problem first.

like image 480
sawa Avatar asked Dec 27 '11 21:12

sawa


1 Answers

There's a bit of confusion here.

Zero is not an acceptable value for line width. The spec dictates that if you say lineWidth = 0 that it will be a no-op.

Furthermore you are not using lineWidth there because you are not stroking. fill() does not take line width into account.

As for the other issue, all you have to do is call beginPath! See here:

http://jsfiddle.net/JfcDL/

Just adding the beginPath call and you'll get this with your code:

enter image description here

What you were doing incorrectly was drawing the entire path so far with every new stroke(). You need to call beginPath to open a new one so that the stroke only applies to the last part and not all the parts made so far.

like image 120
Simon Sarris Avatar answered Oct 26 '22 23:10

Simon Sarris