我的代码有问题。它是一个简单的 Canvas 元素,绘制圆圈。有两件事我无法弄清楚。第一个是如何在按住鼠标左键的同时连续绘制圆圈(一次不是一个)。 “Onmousehold”在这里似乎不起作用。其次,是否可以消除控制台中的第一个引用错误?当尚未指定单击坐标时,它仅出现一次。我的代码在这里:
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
}
outer.addEventListener("click",getMousePos);
outer.addEventListener("click",showBox);
outer.addEventListener("mousedown",showBox);
#outer {
position:relative;
overflow: hidden;
border: 1px solid green;
}
.popup {
width: 50px;
height: 50px;
border-radius: 25px;
background-color: blue;
position: absolute;
}
<canvas id="outer" width="600" height="600">
</canvas>
还有jsfiddle jsfiddle
最佳答案
看到这个:http://jsfiddle.net/4ovgzk07/2/
var outer = document.getElementById("outer");
var ctx = outer.getContext("2d");
function getMousePos(e) {
var cursorX = e.clientX;
var cursorY = e.clientY;
x = cursorX;
y = cursorY;
}
function showBox() {
ctx.beginPath();
ctx.arc(x,y,20,0,2*Math.PI);
ctx.stroke();
console.log(x,y);
outer.addEventListener("mousemove",getMousePos);
outer.addEventListener("mousemove",showBox)
outer.addEventListener("mouseup",removelisteners);
}
function removelisteners() {
outer.removeEventListener("mousemove",getMousePos);
outer.removeEventListener("mousemove",showBox)
}
outer.addEventListener("mousedown",getMousePos);
outer.addEventListener("mousedown",showBox);
;
您需要附加 mousemove
的事件当mousedown
发生时,同样删除那些 events
上mouseup
关于JavaScript Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28557234/