canvas getContext("2d") 返回 null [英] canvas getContext("2d") returns null

查看:196
本文介绍了canvas getContext("2d") 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了几种不同的方法,但我一直遇到同样的错误.我之前已将图像加载到画布上,但自从几天前更新 Safari 以来,我遇到了错误.

I've tried this a few different ways, but I keep getting stuck with the same error. I've loaded an image to canvas before, but since I updated Safari a few days ago, I'm getting errors.

我将发布我目前拥有的内容,但我尝试使用 jQuery、html 的 onLoad 属性等来实现.

I'll post what I have at the moment, but I've tried doing it with jQuery, html's onLoad property, etc.

var cvs, ctx, img;
function init() {
   cvs = document.getElementById("profilecanvas");
   ctx = cvs.getContext("2d"); /* Error in getContext("2d") */
   img = document.getElementById("profileImg");
   drawImg();
}

function drawImg() {
   ctx.drawImage(img, 0, 0);
}

window.onload = init();

ID 是正确的并且对应于适当的 canvas 和 img 标签.但是,我不断收到 TypeError: 'null' is not an object (evaluating 'cvs.getContext') 并且它似乎没有进一步发展.我确定这是一些 ID10T 错误,但我希望有人能告诉我是什么原因造成的?谢谢.

The IDs are correct and correspond to appropriate canvas and img tags. However, I keep getting TypeError: 'null' is not an object (evaluating 'cvs.getContext') and it doesn't seem to be getting any further. I'm sure it's some ID10T error, but I'm hoping someone can give me a clue as to what's causing this? Thank you.

好的,现在这似乎可以使用 工作.但是,它只是偶尔显示,如果我尝试从 $(document).ready()document.onload 运行 init()> 我仍然没有运气,并收到错误.有什么想法吗?

Okay, so this seems to work using <body onload="init()"> now. However, it only displays occasionally, and if I try to run init() off of $(document).ready() or document.onload I still have no luck, and receive the error. Any thoughts?

推荐答案

当你这样做时:

window.onload = init();

函数 init() 将立即执行(导致错误的原因,因为 getContext() 被调用得太早,即在加载 DOM 之前),并且init() 的返回值将存储到 window.onload 中.

the function init() will be executed immediately (what causes the error, because getContext() gets called too early, i.e. before the DOM is loaded), and the return value of init() will be stored to window.onload.

所以你想真正做到这一点:

So you want to actually do this:

window.onload = init;

注意缺少的().

这篇关于canvas getContext("2d") 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆