html5问题中画布上的事件监听器 [英] event listener on canvas in html5 issue
本文介绍了html5问题中画布上的事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是html5中的新手,我想在我的鼠标上创建一个事件监听器,我已经编写了以下代码,但是无法理解y,我无法在我的canvas元素上创建事件监听器,请帮助
i am new in html5 , i want to create a event listener on my mouse , i have written the following code , but cannot understand y , i cant create the event listener on my canvas element , kindly help
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);
根据我想要给我的事件监听器代码,可能也有错误
in light of a ans i want give me event listener code also , may be it has a error also
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();
}
}
推荐答案
您想要将事件添加到画布,而不是2d上下文:
You want to add the event to your canvas, not the 2d context:
canvas_simple.addEventListener('mousemove', ev_mousemove, false);
这是一个演示: jsFiddle链接
Here is a demo: jsFiddle link
这篇关于html5问题中画布上的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文