1

我有以下脚本,它总是完美地工作,只是突然它把线分成两半并向后放一半(http://jsfiddle.net/SQKVG/

html:

<!DOCTYPE HTML> 
<html>  
        <head>  
          <title>Canvas timer</title>  
        </head>
        <body>  
            <div id="timers">
                <canvas id="timer" width="100" height="100"></canvas> 
                <span id="counter">3:00</span> 
            </div>
        </body>  
    </html>  

CSS:

   #timers canvas {
   -webkit-transform : rotate(-90deg);  
   -moz-transform : rotate(-90deg);
}
body{
    background-color: #242424;
}
#timers {
    position: relative; z-index: 1; height: 70px; width: 70px; }
#timers span { 
    position   : absolute; 
    z-index    : 1; 
    top        : 50%; 
    margin-top : -0.6em;
    display    : block; 
    width      : 100%;
    text-align : center;
    height     : 1.5em;
    color      : #528f20;
    font       : 1.3em Arial;
}

查询:

window.onload = function() {
    canvas  = document.getElementById('timer'),
    seconds = document.getElementById('counter'),
    ctx     = canvas.getContext('2d'), 
    sec     = 180,
    countdown = sec;

ctx.lineWidth = 10;
ctx.strokeStyle = "#528f20";

var 
startAngle = 0, 
time       = 0,
intv       = setInterval(function(){

    ctx.clearRect(0, 0, 200, 200);
    var endAngle = (Math.PI * time * 2 / sec);
    ctx.arc(65, 35, 30, startAngle , endAngle, false);   
    startAngle = endAngle;
    ctx.stroke();

    countdown--;
    if ( countdown > 60){
    seconds.innerHTML = Math.floor(countdown/60);
    seconds.innerHTML += ":" + countdown%60;
    }
    else{
    seconds.innerHTML = countdown;
    }

    if (++time > sec,countdown == 0 ) { clearInterval(intv), $("#timer, #counter").remove(), $("#timers").prepend('<img id="theImg" src="http://ivojonkers.com/votify/upvote.png" />'); }



}, 10);

}

有人可以解释一下为什么会这样吗?

4

1 回答 1

2

2个修复:

  • 绘制路径(如弧线)时,您需要 ctx.beginPath
  • 不要在动画循环内重置起始角度

那么你的应用应该没问题:

    ctx.clearRect(0, 0, 200, 200);
    ctx.beginPath();
    var endAngle = (Math.PI * time * 2 / sec);
    ctx.arc(65, 35, 30, startAngle , endAngle, false);   
    //startAngle = endAngle;
    ctx.stroke();
于 2013-10-16T15:47:53.087 回答