如何将事件添加到canvas元素?

时间:2013-12-24 15:17:35

标签: javascript html5 canvas

我有以下代码: 为什么我的ondrop,ondragover和onclick功能不起作用?不工作我的意思是他们应该允许从我的应用程序的另一部分拖放照片。

function mattes_draw_letter(x, y, width, height, letter, position) {
    var canvas = document.createElement('canvas');
    canvas.style.position = "absolute";
    canvas.style.top = 0 + "px";
    canvas.id = "opening_" + position;
    canvas.ondrop = function (event) {
        drop(event, this);
    };
    canvas.ondragover = function (event) {
        allowDrop(event);
    };
    canvas.onclick = function (event) {
        photos_add_selected_fid(this);
    };
    var ctx = canvas.getContext("2d");
    ctx.lineWidth = 1;
    ctx.fillStyle = '#bfbfbf';
    ctx.strokeStyle = '#000000';
    ctx.beginPath();
    ctx.moveTo(x + letter[0] * width, y + letter[1] * height);
    for (i = 0; i < letter.length; i += 2) {
        if (typeof letter[i + 3] !== 'undefined') {
            ctx.lineTo(x + letter[i + 2] * width, y + letter[i + 3] * height);
        }
    }
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    $("#mattes").append(canvas);
}

1 个答案:

答案 0 :(得分:0)

我将代码更改为:

...
$("#mattes").append(canvas);
canvas.addEventListener("drop", function(event) {drop(event, this);}, false); 
canvas.addEventListener("dragover", function(event) {allowDrop(event);}, false); 
canvas.addEventListener("click", function() {photos_add_selected_fid(this);}, false);