gpt4 book ai didi

javascript - 为什么这个clearInterval没有到达var,尽管它被设置为全局的?

转载 作者:行者123 更新时间:2023-11-28 20:04:30 26 4
gpt4 key购买 nike

JSFiddle

创建每个圆形对象后,当鼠标按下时,它的大小应该增加,当鼠标抬起时停止。 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);
}

最佳答案

var growLoop = setInterval(animate, 100);

通过在此处添加 var,您将声明一个也名为 growLoop 的内部变量,并且不会分配给全局变量。删除 var

growLoop = setInterval(animate, 100);

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

关于javascript - 为什么这个clearInterval没有到达var,尽管它被设置为全局的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21070600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com