2013-09-24 44 views
1

我需要在運行時動態創建多個畫布元素。我已經設法創建畫布'很好,但將'onmousedown'屬性設置爲方法已被證明是困難的。這可能是我需要通過該功能傳遞畫布元素的細菌,儘管我不確定。誰能幫忙?動態創建畫布並添加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; 
} 

回答

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)" ... 
              ^^^^^ 
+0

真棒!工作得很好,謝謝! – JamesT