event listener on canvas in html5 issue
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开发者_C百科 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();
}
}
You want to add the event to your canvas, not the 2d context:
canvas_simple.addEventListener('mousemove', ev_mousemove, false);
Here is a demo: jsFiddle link
There are a few mistakes:
You cannot attach the listener to the context, listeners can only be attached to: a single node in a document, the document itself, a window, or an XMLHttpRequest. So you should attach it to the canvas element.
You cannot nest canvas
The canvasHeight property is not defined
I created a jsfiddle with your example modified and working --> here
精彩评论