我是html5中的新手,我想在我的鼠标上创建一个事件监听器,我已经编写了以下代码,但是无法理解y,我无法在我的canvas元素上创建事件监听器,请帮助
var canvasDiv = document.getElementById('canvas');
canvas_simple = document.createElement('canvas');
canvas_simple.setAttribute('height', canvasHeight);
canvas_simple.setAttribute('id', 'canvasSimple');
canvasDiv.appendChild(canvas_simple);
if(typeof G_vmlCanvasManager != 'undefined')
{
canvas_simple = G_vmlCanvasManager.initElement(canvas_simple);
}
context_simple = canvas_simple.getContext("2d");
context_simple.addEventListener('mousemove', ev_mousemove, false);
根据我想要给我的事件监听器代码,也可能是它也有错误
var started = false;
function ev_mousemove (ev) {
var x, y;
if (ev.layerX || ev.layerX == 0) { // Firefox
x = ev.layerX;
y = ev.layerY;
}
else if (ev.offsetX || ev.offsetX == 0) { // Opera
x = ev.offsetX;
y = ev.offsetY;
}
if (!started) {
context.beginPath();
context.moveTo(x, y);
started = true;
}
else {
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 10;
context.lineTo(x, y);
context.stroke();
}
}
答案 0 :(得分:4)
您想要将事件添加到画布,而不是2d上下文:
canvas_simple.addEventListener('mousemove', ev_mousemove, false);
以下是演示:jsFiddle link
答案 1 :(得分:1)
有一些错误:
您无法将侦听器附加到上下文,侦听器只能附加到:文档中的单个节点,文档本身,窗口或XMLHttpRequest。所以你应该把它附加到canvas元素。
你不能嵌套画布
未定义canvasHeight属性
我创建了一个jsfiddle,你的例子经过修改和工作 - > here