当值被硬编码时代码工作,但当它从 DOM 中使用 getElementByID("x") 获取时代码不工作
Code is working when value is hard coded but is not working when it is taken from the DOM with getElementByID("x")
这是我遇到问题的函数,它使用的是 p5.js 库。
function SprayCanTool(){
this.name = "sprayCanTool";
this.icon = "assets/sprayCan.jpg";
var spread ;
var points = 13 ;
this.draw = function(){
var r = random(5,10);
spread = document.getElementById("size-slider").value;
if(mouseIsPressed){
for(var i = 0; i < points; i++){
point(random(mouseX-spread, mouseX + spread),random(mouseY-spread, mouseY+spread));
}
}
};
this.populateOptions = function(){
select(".options").html( " <label>Size of Spray: </label> <input id='size-slider' type='range' min='10' max='200' step='1' value='10'> ");
}
}
如上所示,代码不起作用,我无法调整喷雾的大小,喷雾根本不会显示在 canvas 上。
如上所示,最小值差可以是 10。当我将 console.log(spread,points)
添加到 draw 方法中时,预期的 10,13
会输出到控制台。
当我将该值硬编码为任何数字并删除 spread = document.getElementById("size-slider").value;
部分时,代码按我预期的方式工作(当然我无法使用滑块调整大小)
有谁知道是什么导致了这个问题?
没关系,我的谜题现在已经解开了。我找错了地方,我收到错误是因为我试图用浮点数添加整数,并且由于某种原因使用 javascript 将它们加在一起,就像它们都是字符串一样。
我已经通过更换解决了我的问题:
point(random(mouseX-spread, mouseX + spread),random(mouseY-spread, mouseY+spread));
和
point(random(int(mouseX)-int(spread), int(mouseX) + int(spread)),random(int(mouseY)-int(spread), int(mouseY)+int(spread)))
这是我遇到问题的函数,它使用的是 p5.js 库。
function SprayCanTool(){
this.name = "sprayCanTool";
this.icon = "assets/sprayCan.jpg";
var spread ;
var points = 13 ;
this.draw = function(){
var r = random(5,10);
spread = document.getElementById("size-slider").value;
if(mouseIsPressed){
for(var i = 0; i < points; i++){
point(random(mouseX-spread, mouseX + spread),random(mouseY-spread, mouseY+spread));
}
}
};
this.populateOptions = function(){
select(".options").html( " <label>Size of Spray: </label> <input id='size-slider' type='range' min='10' max='200' step='1' value='10'> ");
}
}
如上所示,代码不起作用,我无法调整喷雾的大小,喷雾根本不会显示在 canvas 上。
如上所示,最小值差可以是 10。当我将 console.log(spread,points)
添加到 draw 方法中时,预期的 10,13
会输出到控制台。
当我将该值硬编码为任何数字并删除 spread = document.getElementById("size-slider").value;
部分时,代码按我预期的方式工作(当然我无法使用滑块调整大小)
有谁知道是什么导致了这个问题?
没关系,我的谜题现在已经解开了。我找错了地方,我收到错误是因为我试图用浮点数添加整数,并且由于某种原因使用 javascript 将它们加在一起,就像它们都是字符串一样。
我已经通过更换解决了我的问题:
point(random(mouseX-spread, mouseX + spread),random(mouseY-spread, mouseY+spread));
和
point(random(int(mouseX)-int(spread), int(mouseX) + int(spread)),random(int(mouseY)-int(spread), int(mouseY)+int(spread)))