动态创建画布并添加鼠标按下功能

Dynamically create Canvas and add onmousedown functionality

本文关键字:鼠标 功能 添加 创建 动态      更新时间:2023-09-26

我需要在运行时动态创建多个画布元素。我已经设法很好地创建了画布,但是将"onmousedown"属性设置为一种方法已被证明是困难的。这可能是我需要通过函数传递 canvas 元素的 bacuse,尽管我不确定。谁能帮忙?

谢谢!

下面您可以按顺序看到:原始静态画布,动态创建画布的循环以及我需要设置为"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);
}

请注意,这只会给出一个参数,即事件。但是没有必要,因为回调会将调用回调的当前画布绑定为 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)" ...
                                            ^^^^^