开发者

I am playing with canvas. How do I get it to work?

Here is my html:

<canvas id="test" width="400" height="200"></canvas>

here is my javascript:

var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext开发者_运维问答("2d");
canvas_context.fillRect(50, 25, 150, 100);

I am just experimenting with this and none of the tutorials seem to be working. I am using chrome as my browser fyi.

The original typo was only on here; not in my editor. Sorry about that.

I am getting the error: Uncaught TypeError: Cannot call method 'getContext' of null even with the jsfiddle example.

Ok I figured out what was wrong. Because my javascript was in the head of the html file, it was being loaded before the DOM was completely loaded, So when it tried to do var canvas_one = document.getElementById("test"); it set canvas_one to null. So what I did is just wrap it in jquery like this:

$(document).ready(function(){
var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext("2d");

canvas_context.fillStyle = "rgb(255,0,0)";
canvas_context.fillRect(10, 25, 150, 100);

});

Now it waits for the DOM to load before it reads the javascript and everything works.


The mozilla tutorial is the best one in my opinion, try it.

Correct the following: document.getElementById, you just typed it wrong.


Make sure any code which references the DOM executes only after the DOM is ready. This can be achieved by wrapping everything in a function which is called using window.onload, or by using jQuery or a similar library to do this for you.


You have a typo for getElementById, also I suggest setting a fillStyle as well.

Live Demo

var canvas_one = document.getElementById("test");
var canvas_context = canvas_one.getContext("2d");

canvas_context.fillStyle = "rgb(255,0,0)";
canvas_context.fillRect(10, 25, 150, 100);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜