无法通过jQuery获取Canvas更新

时间:2012-08-21 17:55:29

标签: jquery html5 canvas

我正在尝试制作一个以零半径开始的圆形笔画动画,最终变成一个完整的半径。

我正在尝试使用HTML5 Canvas和jQuery。圆圈被绘制一次,但没有动画。

脚本:

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)
});

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>

2 个答案:

答案 0 :(得分:3)

考虑到你提供的角度,你只是在错误的方向上绘制弧线。

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

而不是

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

答案 1 :(得分:1)

您的代码中存在一些问题。

  1. 您不应每次都实例化上下文。
  2. 你永远不会清除画布。
  3. 你没有画出你想要的东西,比如@dystroy
  4. http://jsfiddle.net/lechevalierd3on/REqy6/

    1。 将canvas和ctx var保持在更高的范围内&#34;。把它们放在全球范围内也不是一个好习惯。最好的方法是将所有东西包装成一个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。 在这种情况下,由于您在彼此之上绘制弧线,因此您无法看到它。但你可以猜测别名。

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