gpt4 book ai didi

javascript - html5 问题中 Canvas 上的事件监听器

转载 作者:搜寻专家 更新时间:2023-10-31 23:12:05 25 4
gpt4 key购买 nike

我是 html5 的新手,我想在我的鼠标上创建一个事件监听器,我已经编写了以下代码,但无法理解你,我无法在我的 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();
}

最佳答案

您想将事件添加到 Canvas ,而不是 2d 上下文:

canvas_simple.addEventListener('mousemove', ev_mousemove, false);

这是一个演示:jsFiddle link

关于javascript - html5 问题中 Canvas 上的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7337759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com