2014-01-12 39 views
0

JSFiddle爲什麼clearInterval沒有達到var,儘管它被設置爲全局?

創建每個圓形對象後,鼠標停止時應增加大小,鼠標停止時應停止。 clearInterval似乎沒有達到內部變量「growLoop」,即使它首先聲明爲全局的(這是關於同一問題的許多其他帖子的建議)。在控制檯中,它顯示growLoop未定義,但它在第95行中定義,對吧? 此外,時間間隔似乎隨着創建的每個新圈子而減少,並且它們增長得更快。 setInterval的值如何改變?

//set up canvas 
    var canvas = document.getElementById("canvas"); 
    var ctx = canvas.getContext("2d"); 

var circles = []; 

//create circle 
function create(location) { 
    circles.push({ 
     x: location.x, 
     y: location.y, 
     radius: 10, 
     color: '#' + Math.floor(Math.random() * 16777215).toString(16) 
    }); 
} 

//figure out mouse position 
var rect = document.getElementById("canvas").getBoundingClientRect(); 
// Get canvas offset on page 
var offset = { 
    x: rect.left, 
    y: rect.top 
}; 

function isOnCanvas(a) { 
    if ((a.x >= 0 && a.x <= rect.width) && (a.y >= 0 && a.y <= rect.height)) { 
     return true; 
    } 
    return false; 
} 

function isOnCircle(a) { 
    var i = 0, 
     l = circles.length, 
     x, y, d, c; 
    for (; i < l; ++i) { 
     c = circles[i]; 
     x = a.x - c.x; 
     y = a.y - c.y; 
     d = (a.radius || 10) + c.radius; 
     if (x * x + y * y <= d * d) { 
      return true; 
     } 
    } 
    return false; 
} 

// draw all circles 
function draw() { 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    for (var i = 0; i < circles.length; i++) { 
     var p = circles[i]; 
     ctx.beginPath(); 
     ctx.arc(p.x, p.y, p.radius, 0, 2 * Math.PI); 
     ctx.fillStyle = p.color; 
     ctx.fill(); 
    } 
} 

//make last drawn circle 1px bigger 
function grow(){ 
    var a = circles[circles.length-1]; 
     a.radius += 1; 
} 

//find percentage of canvas filled in 
var totalSpace = canvas.width * canvas.height; 
var totalFilled = function() { 
    total = 0; 
    for (var i = 0; i < circles.length; i++) { 
     var p = circles[i]; 
     total += Math.PI * Math.pow(p.radius, 2); 
    } 
    return total; 
    console.log(total); 
} 

    function findPercentage() { 
     return (totalFilled()/totalSpace) * 100; 
    } 

    function updateInfo() { 
     percentage = findPercentage(); 
     document.getElementById("percentage").innerHTML = "You've filled in " + percentage.toFixed(1) + "%"; 
    } 

//do all the stuff 
var animate = function(){ 
    draw(); 
    grow(); 
    updateInfo();} 
var growLoop = 0; 

window.onmousedown = function (e) { 
    // get event location on page offset by canvas location 
    var location = { 
     x: e.pageX - offset.x, 
     y: e.pageY - offset.y 
    }; 

    if (isOnCanvas(location) && !isOnCircle(location)) { 
     create(location); 
     var growLoop = setInterval(animate, 100); 
    } 
}; 

window.onmouseup = function (e) { 
    clearInterval(growLoop); 
} 
window.onmouseout = function (e) { 
    clearInterval(growLoop); 
} 

回答

3
var growLoop = setInterval(animate, 100); 

通過添加var這裏你聲明的內部變量也叫growLoop,而不是分配給全球。刪除var

growLoop = setInterval(animate, 100); 

http://jsfiddle.net/SeAGU/85/

相關問題