1

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

谢谢!

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

1 回答 1

1

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

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)" ...
                                            ^^^^^
于 2013-09-24T08:51:32.020 回答