动态创建Canvas并添加onmousedown功能

时间:2013-09-24 08:28:24

标签: javascript html5 canvas

我需要在运行时动态创建多个canvas元素。我已经设法创建画布'很好,但是将'onmousedown'属性设置为方法已经证明是困难的。这可能是我需要通过函数传递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;
}

1 个答案:

答案 0 :(得分: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)" ...
                                            ^^^^^