画布/上下文问题
我正在使用标签创建文档,但遇到问题。 我已将画布和上下文声明为全局变量,并将它们填充到我的初始函数中。这似乎部分有效,但某些函数(例如,调用画布宽度的函数)给了我错误:“Cannot call method getAttribute on null”
这是因为我尝试设置文档这样?我尝试在定义时填充它们(就像它们可以用于局部变量一样),但这似乎会产生同样多的错误!
我像这样声明变量:
var canvas = null;
var context = null;
并将它们填充到链接到主体 onload 的函数中,如下所示:
canvas = document.getElementById("imageDisplay");
context = canvas.getContext("2d");
我应该像这样为每个使用它们的函数重新填充它们吗?
昨天我在另一段脚本中使用了几乎完全相同的方法,效果很好!我不明白我做错了什么!
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题可能是范围界定问题。
根或窗口 javascript
函数 foo
如果我的理解(javascript 和你的问题)是正确的,则画布未定义,因为 foo.canvas 与 window.canvas 不同。您要么需要在 foo 中重新声明 canvas 和 context,要么使用 window.canvas 和 window.context,或者传入这些变量。我是 javascript 的新手,所以希望其他人可以调解
Your issue might be a scoping issue.
root or window javascript
function foo
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