有人可以给我一些帮助吗?,我不明白为什么它不起作用,我尝试了所有方法,但我就是不明白,我是初学者。
我正在尝试为画布绘画制作一个保持鼠标事件,我尝试制作一个循环,你握住它,它会在画布上绘画,但它不起作用,所以我尝试让循环在控制台中说"你好"......但它不起作用。
document.addEventListener("mousedown", holding)
document.addEventListener("mouseup", noHolding)
var hold;
function holding(){
hold = true;
console.log("hold: " + hold)
}
function noHolding(){
hold = false;
console.log("hold: " + hold)
}
while(hold == true){
console.log("Holding")
}
你必须考虑执行的顺序。 您的代码逐行执行(或多或少(。因此,在您的示例中,这些是步骤:
- 声明函数
holding
- 声明函数
noHolding
- 声明变量
hold
- 将
holding
绑定到mousedown
事件 - 将
noHolding
绑定到moueup
事件 - 定义函数
holding
- 定义函数
noHolding
hold == true
时循环- 此时的 hold 值为
undefined
,因此循环不会运行
- 此时的 hold 值为
- 完成执行
function
和var
声明被移动(提升(到其函数的顶部,如果不在函数范围内,则被移动(提升(到全局范围。
稍后,当您按下鼠标按钮时hold
将设置为true
但while(hold==true)
语句已经执行并且不会再次运行。
您应该避免在 javascript 中运行超过几毫秒的循环,因为它们会阻止任何其他代码运行(通常(。
您可以改用鼠标移动事件。(包括示例(
来自 MDN 的例子:
// When true, moving the mouse draws on the canvas
let isDrawing = false;
let x = 0;
let y = 0;
const myPics = document.getElementById('myPics');
const context = myPics.getContext('2d');
// The x and y offset of the canvas from the edge of the page
const rect = myPics.getBoundingClientRect();
// Add the event listeners for mousedown, mousemove, and mouseup
myPics.addEventListener('mousedown', e => {
x = e.clientX - rect.left;
y = e.clientY - rect.top;
isDrawing = true;
});
myPics.addEventListener('mousemove', e => {
if (isDrawing === true) {
drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
x = e.clientX - rect.left;
y = e.clientY - rect.top;
}
});
window.addEventListener('mouseup', e => {
if (isDrawing === true) {
drawLine(context, x, y, e.clientX - rect.left, e.clientY - rect.top);
x = 0;
y = 0;
isDrawing = false;
}
});
function drawLine(context, x1, y1, x2, y2) {
context.beginPath();
context.strokeStyle = 'black';
context.lineWidth = 1;
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
context.closePath();
}
canvas {
border: 1px solid black;
width: 560px;
height: 360px;
}
<h1>Drawing with mouse events</h1>
<canvas id="myPics" width="560" height="360"></canvas>