2

我正在 SharePoint 中开发一个 WebPart,我需要使用 excanvas.js 在我的 WebPart 中绘制一些东西。但有时它什么也不显示。错误消息是:

Object doesn't support property or method 'getContext'

当我调试它时,它在这里中断:

var ctxBg = document.getElementById(backgroundId).getContext("2d");

“backgroundId”是一个画布元素的 id。这个错误不是每次都发生,只是有时,所以我想如果我的js函数在excanvas.js加载之前执行。我用代码注册excanvas.js:

this.Page.ClientScript.RegisterClientScriptInclude("ExCanvasJs", "wpresources/MyWebPart/js/excanvas.js");

那么如何确保我的函数在加载excanvas.js后执行?或者我在这个问题上错了?你能给我你的建议吗?

我的js函数:

function DrawMeter(meter, contextCollection) {
var backgroundId = meter.meterbackground;
var pointerId = meter.meterpointer;
var containerId = meter.metercontainer;
if (contextCollection != null && contextCollection.length > 0) {
    for (var i = 0; i < contextCollection.length; i++) {                    
        DrawSingleMeter(backgroundId + "_" + i, pointerId + "_" + i, containerId + "_" + i, contextCollection[i]);
    }
}

function DrawSingleMeter(backgroundId, pointerId, containerId, context) {
var ctxBg = document.getElementById(backgroundId).getContext("2d");
var ctxPointer = document.getElementById(pointerId).getContext("2d");
drawing...

}

4

1 回答 1

1

you need to put it into a page ready handler. otherwise at the time the javascript is executed the element might not be available yet.
consider using jquery or another js library for this, if you can't use it here's a link on how to use the native js version of the onload event

于 2012-02-05T11:14:13.897 回答