画布/上下文问题

发布于 2024-10-18 13:38:36 字数 531 浏览 1 评论 0原文

我正在使用标签创建文档,但遇到问题。 我已将画布和上下文声明为全局变量,并将它们填充到我的初始函数中。这似乎部分有效,但某些函数(例如,调用画布宽度的函数)给了我错误:“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

合久必婚 2024-10-25 13:38:36

您的问题可能是范围界定问题。

根或窗口 javascript

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

foo();

函数 foo

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

如果我的理解(javascript 和你的问题)是正确的,则画布未定义,因为 foo.canvas 与 window.canvas 不同。您要么需要在 foo 中重新声明 canvas 和 context,要么使用 window.canvas 和 window.context,或者传入这些变量。我是 javascript 的新手,所以希望其他人可以调解

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文