2013-10-16 28 views
1

我在下面的腳本,它總是可以正常使用纔剛剛突然它將該線減半,並提出一個半向後(http://jsfiddle.net/SQKVG/jQuery的畫布反

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

的Jquery:

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

} 

有人可以解釋爲什麼會發生這種情況嗎?

回答

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