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

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

问题描述

我尝试过这几种不同的方法,但我仍然遇到相同的错误。我之前已经加载了一个图像到canvas,但是从几天前我更新了Safari,我收到了错误。



我会发布我在时间,但我已经尝试用jQuery,html的onLoad属性等。

  var cvs,ctx,img; 
function init(){
cvs = document.getElementById(profilecanvas);
ctx = cvs.getContext(2d); / * getContext(2d)中的错误* /
img = document.getElementById(profileImg);
drawImg();
}

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

window.onload = init();

ID是正确的,对应于适当的canvas和img标签。但是,我一直得到 TypeError:'null'不是一个对象(评估'cvs.getContext'),它似乎没有得到任何进一步。我相信它是一些ID10T错误,但我希望有人可以给我一个线索,这是什么引起的?谢谢。



编辑:
好​​吧,所以这似乎工作使用< body onload =init()> 现在。但是,它只是偶尔显示,如果我尝试运行 $(document).ready() c>或 document.onload 我还是没有运气,并收到错误。任何想法?

解决方案

执行此操作时:

  window.onload = init(); 

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



this:

  window.onload = init; 

注意缺少的() p>

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.

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();

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.

Edit: 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?

解决方案

When you do this:

window.onload = init();

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;

Note the missing ().

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

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