开发者

Canvas/Context issues

I am creating a document using the tag and am having an issue. I have declared canvas and context as global variables and am filling them in my initial function. This seems to work partially, but certain functions开发者_运维百科 (for instance, one calling the canvas width) are giving me the error: "Cannot call method getAttribute on null"

Is this because I have tried setting up the document in this way? I tried filling them when defined (like they can be for a local variable) but this seemed to produce just as many errors!

I am declaring the variables like so:

var canvas = null;
var context = null;

And filling them in the function which is linked to the body onload like so:

canvas = document.getElementById("imageDisplay");
context = canvas.getContext("2d");

Should I be re-filling them like this for every function that uses them?

I was using almost the exact same methods in another piece of script yesterday which worked fine! I don't understand what I've done wrong!

Thanks


Your issue might be a scoping issue.

root or window javascript

var canvas;
var context;
canvas = document.getElementById("imageDisplay");
context = canvas.getContext("2d");

foo();

function foo

foo{
    canvas = document.getElementById("imageDisplay");//errors
    context = canvas.getContext("2d");
}

If my understanding (both of javascript and your issue) is correct canvas isn't defined because foo.canvas is different from window.canvas. You either need to re-declare canvas and context in foo, or use window.canvas and window.context, or pass in those variables. I am a bit of a novice at javascript so hopefully someone else can intercede

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜