gpt4 book ai didi

javascript - 动态创建Canvas并添加onmousedown功能

转载 作者:行者123 更新时间:2023-11-28 01:57:02 27 4
gpt4 key购买 nike

我需要在运行时动态创建多个 Canvas 元素。我已经成功地创建了 Canvas ,但将“onmousedown”属性设置为方法已证明很困难。这可能是因为我需要通过函数传递 Canvas 元素,尽管我不确定。有人可以帮忙吗?

谢谢!

下面您可以按顺序看到:原始静态 Canvas 、动态创建 Canvas 的循环以及我需要设置为“onmousedown”的函数。

<canvas id="Canvas1" onmousedown="MouseDown(this, event)" onmousemove="MouseMove(event)" onmouseup="MouseUp(event)" width="0" height="600" style="overflow: hidden; position: absolute; top: 0px;">

for(var i = 1; i < total; i++)
{
var div = document.getElementById("Control");
var canv = document.createElement('canvas');
canv.id = "Canvas" + i.toString();
canv.width= 0+'px';
canv.height= 600+'px';
canv.style.overflow = 'hidden';
canv.style.position = 'absolute';
canv.style.top = 0+'px';

div.appendChild(canv);
}

function MouseDown(can, e)
{

MovingCanvas = can;
alert("got here");
clicked = true;
MouseX = e.clientX;
MouseY = e.clientY;

StartX = MovingCanvas.style.left;
StartY = MovingCanvas.style.top;
}

最佳答案

只需在循环内添加回调处理程序:

for(var i = 1; i < total; i++) {

--- 8X ---

/// add a callback handler here by referencing the function
canv.onmousedown = MouseDown;

div.appendChild(canv);
}

请注意,这只会给出一个参数,即事件。但没有必要,因为回调会将调用回调的当前 Canvas 绑定(bind)为 this;所以你可以修改你的回调函数:

/// callback only gives one argument to the function, the event
function MouseDown(e) {

/// this will be current canvas that called this function
MovingCanvas = this;

--- 8X ---
}

当然这也需要修改:

<canvas id="Canvas1" onmousedown="MouseDown(event)" ...
^^^^^

关于javascript - 动态创建Canvas并添加onmousedown功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976517/

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