1

我正在尝试像在 jquery 中一样将我自己的对象参数添加到画布元素中(就像它将 element_id.draggable、element_id.resizable 等添加到 dom 元素中一样)。我的一段代码如下所示:

window.addEventListener("DOMContentLoaded",handler,false);
function handler()
{
     HTMLCanvasElement.prototype.animateLine=function(x1,x2,y1,y2,params) {
     if(params)
             init(this,x1,x2,y1,y2,params.lineColour,params.lineWidth,params.divisions,params.totalTime,params.callback);
     else
             init(this,x1,x2,y1,y2);
     };
}

这样当用户声明一个canvas标签时,就可以直接调用canvas_id.animateLine()执行上述函数。

但是出现的问题是,当用户在 body onload 或 window onload 中调用 animateLine() 时,它不起作用(说 animateLine 未定义)。

我想知道这是实现这个的正确方法吗?另外,由于我也必须在 body/window onload 上调用它,因此如何从上面的代码中删除错误?

编辑:更新代码以在 DOM 就绪时调用函数,如果用户在 DOM 就绪时调用 animateLine,它仍然不起作用。有什么解决办法吗?

4

2 回答 2

1

You seem to have 2 problems: You don't really add your init function to window.onload, you'd need to remove the () after onload. Also, it would could be that it is just overwritten by an other assignment. Use proper event listeners instead.

Second, your function is only executed once. It waits for onload, then looks around for all canvas elements it can find (at that time) and adds a (different) function to each of them.

If you really would want to add a function to every canvas element ever existing (you could dynamically create them), you would need to add your methods to HTMLCanvasElement.prototype. Yet, there is a good article about What’s wrong with extending the DOM. Read it and use another solution, e.g. the proposed object wrappers. If you use jQuery or some lib like that, you could write animateLine as a plugin for that.

于 2012-05-17T12:18:00.530 回答
0

将函数分配给事件的正确方法如下:

window.onload = function() {...};

此外,将东西(函数、对象、数组等)直接附加到 DOM 元素也不好。更好地创建一个对元素进行操作的“接口”:

function ACanvas(id){

    //internal reference
    var canvas = document.getElementById('id');

    //the public interface
    return {
        draw : function(){
            //drawing logic that operates on "canvas"
        },
        erase : function(){
            //erase logic that operates on "canvas"
        }
    }
}

var myCanvas = ACanvas('mycanvasid'); //wrap the element
myCanvas.draw();                      //operate
myCanvas.erase();                     //operate
于 2012-05-17T12:14:44.837 回答