Reputation: 21
I'm facing a problem when i want to get the context of a canvas. Here is the HTML code:
<canvas id="thecanvas" width="600" height="300"></canvas>
and the Javascript:
var canvaso = document.getElementById('thecanvas');
if (!canvaso) {
alert('Error: Cannot find the canvas element!');
return;
}
if (!canvaso.getContext) {
alert('Error: Canvas context does not exist!');
return;
}
The "canvaso" variable is correctly loaded, but it failed on "canvaso.getContext":
Uncaught TypeError: Object #<HTMLDivElement> has no method 'getContext'
Thanks for your help.
Upvotes: 1
Views: 19645
Reputation: 126
This is probably because you loaded your javascript as an external file in the <head>
block of the page. This means that your javascript ran before the rest of the html elements like the <canvas>
element were loaded. That's why your browser couldn't find any element with the given ID on the page - because the canvas element didn't exist at that point.
There are a few solutions to this:
<script>
block anytime after you declare the <canvas>
block.onload
attribute in the <body>
tag).A sample of the second solution has been shown below:
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="myscript.js"> </script>
</head>
<body onload="test()">
<canvas id="thecanvas" width="600" height="300"></canvas>
</body>
</html>
myscript.js:
function test() {
var canvaso = document.getElementById('thecanvas');
if (!canvaso) {
alert('Error: Cannot find the canvas element!');
return;
}
else if (!canvaso.getContext) {
alert('Error: Canvas context does not exist!');
return;
}
else {
alert('Success!');
}
}
Upvotes: 0
Reputation: 30453
Try this (see Demo: http://jsbin.com/ijazum/1):
<body>
<canvas id="canvas" width="600" height="300"></canvas>
<script>
function getStart() {
var canvas = document.getElementById('canvas');
if (!canvas) {
alert('Error: Cannot find the canvas element!');
return;
}
if (!canvas.getContext) {
alert('Error: Canvas context does not exist!');
return;
}
var ctx = canvas.getContext('2d');
ctx.fillStyle = "#3d3";
ctx.fillRect(0, 0, 100, 100);
}
getStart();
</script>
</body>
Upvotes: 3
Reputation: 6034
Your browser is not HTML5 compliant. A compliant browser would return Object #<HTMLCanvasElement> has no method 'getContext'
(Although the getContext method would work)
Works fine here, are you sure you have a canvas by the id of thecanvas on the same page?
Here is a possibility: do you ever define a div
with the id thecanvas
anywhere in your document, most likely after the canvas? Duplicate IDS are semantically incorrect, and getElementById will return the last occurrence of that Id within the DOM.
Upvotes: 3