rib3ye
rib3ye

Reputation: 2923

Can't get Canvas to update via jQuery

I'm trying to make an animation of a circle stroke that starts with a zero radius that eventually becomes a full radius.

I'm trying to do it using the HTML5 Canvas and jQuery. The circle gets drawn once but doesn't animate.

The script:

function calc(myVal) {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var radius = 70;

    ctx.beginPath();
    ctx.arc(140, 140, 100, myVal * Math.PI, 0, false);
    ctx.lineWidth = 10;
    ctx.stroke();
};
$(document).ready(function() {
    var count = 0;
    var parsedCount;
    function go(){  
        if (count <= 200) {
            parsedCount = count*.01
            $('#counter').html('<p>' + parsedCount + '</p>');
            calc(parsedCount);
            count++;
        }
    }
    setInterval(go, 100)
});

The HTML:

    <canvas id="myCanvas" width="400" height="400" style="border: 1px solid #000">

    </canvas>
    <div id="counter" class="" style="height: 100px; width: 100px; border: 1px solid #000">

    </div>

Upvotes: 1

Views: 1345

Answers (2)

3on
3on

Reputation: 6339

You have a few problems in you code.

  1. You should not instantiate the context every time.
  2. You never clear the canvas.
  3. You are not drawing what you wish, like mentioned by @dystroy

http://jsfiddle.net/lechevalierd3on/REqy6/

1. Keep the canvas and ctx var in a "higher scope". Putting them in the global one is not a good practice either. The best would be to wrap the all thing into an Object.

function Animation() {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  this.draw = function(val) {
   // content of calc
  }

}

var animation = new Animation();
$(function(){
  // what needs to be compute at ready
  // ...

  // setInterval a function that make the call to Animation.draw();

})

2. In this case you don't see it since you draw arcs on top of each others. But you can actually guess aliasing.

ctx.clearRect(0,0,canvas.width, canvas.height);

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You're just drawing the arc in the wrong direction given the angles you provide.

Do

ctx.arc(140, 140, 100, myVal * Math.PI, 0, true);

instead of

ctx.arc(140, 140, 100, myVal * Math.PI, 0, false);

Upvotes: 3

Related Questions