Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - canvas getContext("2d") returns null

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For others who hit this page while searching for getContext returning null, it can happen if you have already requested a different type of context.

For example:

var canvas = ...;
var ctx2d = canvas.getContext('2d');
var ctx3d = canvas.getContext('webgl'); // will always be null

The same is equally true if you reverse the order of calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...