canvas.getContext("2d"); not working - javascript

I am getting the following Error
Error: Uncaught TypeError: Cannot read property 'innerHTML' of null
at script.js:1
I have tried everything I could think of but nothing works.
var canvas = document.getElementById("can").innerHTML;
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas
</body>
</html>

Okay there are two serious errors.
You're trying to get the element before the DOM is fully loaded. Therefore the canvas note is not reachable. See addEventListener
and DOMContentLoaded.
Remove .innerHTML. getContext appends on the node not on the content.
document.addEventListener('DOMContentLoaded', function() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 300, 200);
});
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
</head>
<body>
<script src="script.js"></script>
<!-- Canvas -->
<canvas id="can" width="300" height="200" style="border:4px solid red;">
</canvas>
</body>
</html>

1. Script error when using canvas
Use var canvas = document.getElementById("can");
Not var canvas = document.getElementById("can").innerHTML();
See W3C - Canvas
2. Add an event listener when the document is ready, then execute your script
See W3C - DOM Event Listener example
function doSomething() {
var canvas = document.getElementById("can");
var ctx = canvas.getContext('2d');
/*
another scripts...
*/
}
window.addEventListener('onload', doSomething, false);

There are two things.
First, you don't need .innerHTML as other answers stated.
Second, you either have to run you script at the window load event like so:
window.addEventListener('load', function () {
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.fillStyle = ("green");
ctx.fillRect(0, 0, 300, 200);
});
Or you should load the javascript after the canvas tag.

Related

Property 'getContext' does not exist on type ''HTMLElement"

I am trying to make the background of the canvas but I can't use getContext. I get the error:
Uncaught TypeError: Cannot read property 'getContext' of null at game.js:4
Html
<!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8">
<title>Game</title>
</head>
<body>
<script src="game.js"></script>
<canvas id="canvas" width="100" height="320"></canvas>
</body>
</html>
Javascript
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
I have already tried using the post: Cannot read property 'getContext' of null
but it did not help me.
This is because you are calling your javascript before the element is added to the page/DOM and the browser runs/loads code/HTML synchronously (one line at a time).
So, this leaves us with three options:
Use Defer
Add defer to your script tag this will load it after the dom is ready
<script src="game.js" defer></script>
Move the script tag after the canvas
Moving the tag after the canvas will allow the canvas to be ready when the script runs
<canvas id="canvas" width="100" height="320"></canvas>
<script src="game.js"></script>
Wrap your code within the DOMContentLoaded event
Putting your code within this event will run the code after the DOM has loaded.
document.addEventListener('DOMContentLoaded', e => {
const canvas = document.getElementById('canvas');
if (canvas != null) {
ctx = canvas.getContext("2d");
} else {
console.log('wtf happen');
}
function draw(){
ctx.background(255,0,0);
}
})

How do I fix "TypeError: background is null"? [duplicate]

here's the code:
HTML:
<body onload="initializeMap()">
<div id="map_canvas" style="width:100%; height:100%; z-index:1"></div>
<canvas id="control" style="width:100%; height:100%; z-index:2">Does Not Support Canvas Element</canvas>
</body>
Javascript:
<script type="text/javascript">
var canvas = document.getElementById('control');
var context = canvas.getContext('2d');
function draw(){
context.font = "bold 12px sans-serif";
context.fillText("x", 248, 43);
}
</script>
the draw function is called after initialization of the google map so the DOM should have already loaded by then, correct? What might have I done incorrectly?
The DOM has already been loaded when the draw-function is called, that is correct.
But the var canvas = document.getElementById('control');-line is evaluated before that, because it is not in the draw-function. It is executed immediately in the <head> of the document BEFORE the elements have been rendered.
I would suggest you change your init function to something like that
var canvas,context;
function initializeMap() {
canvas = document.getElementById('control');
context = canvas.getContext('2d');
}
If your javascript is loaded prior to your body then canvas will be undefined because the browser hasn't loaded/rendered it yet.

Uncaught TypeError: Cannot read property 'getContext' of null

In my console I get the error: "Uncaught TypeError: Cannot read property 'getContext' of null"
and I just can't find the error I've made... or what I've done wrong.
So maybe you can help me find it?
Please help :)
enter code here
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var cW = canvas.width = 1000;
var cH = canvas.height = 500;
var particleAmount = 10;
var particles = [];
for(var i=0;i<particleAmount;i++) {
particles.push(new particle());
}
function particle() {
this.x = (Math.random() * (cW-(40*2))) + 40;
this.y = (Math.random() * (cH-(40*2))) + 40;
this.xv = Math.random()*20-10;
this.yv = Math.random()*20-10;
}
function draw () {
ctx.fillStyle = "black";
ctx.fillRect(0,0,cW,cH);
for(var ii=0;ii<particles.length;ii++){
var p = particles[ii];
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(p.x,p.y,40,Math.PI*2,false);
ctx.fill();
}
}
setInterval(draw,30);
The error basically means that the HTML and the JavaScript code aren't cooperating properly, or simply that you haven't loaded the script correctly.
Try this:
function init() {
// Run your javascript code here
}
// Run the 'init' function when the DOM content is loaded
document.addEventListener("DOMContentLoaded", init, false);
Hope this helps.
The answer is in the comments just after the question! Someone else also posted it as an answer a bit below, but all credits to: #elclanrs
"Right, so the canvas doesn't exist yet. Load the script after the canvas element. – elclanrs Sep 13 '14 at 22:43"
I think you put the script tag above of the canvas tag please put it after the canvas tag.
Put the scripts file after the canvas. That means put down your script before the body tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 Canvas</title>
<link rel="shortcut icon" href="assets/1.png">
<link rel="stylesheet" href="assets/canvas.css">
</head>
<body>
<div class="container">
<h2>Canvas</h2>
<canvas id="myCanvas" width="400" height="300">
</canvas> <!-- End Canvas -->
</div> <!-- End Container -->
<script src="canvas.js"></script>
</body>
</html>
Try to declare the canvas element before the script tag. It worked fine for me.

Javascript Onclick Functions

Writing a simple script to have two buttons. One button animates a "painting" feature where rectangles follow the cursor around the canvas. The other button would display a rectangle that follows the canvas but doesn't leave a trail like the other. I have the buttons linked to do different functions. Right now the follow button doesn't work, it does clear the canvas but it still allows you to paint. It seems that the paint function is still running after I hit the follow button. Any help is appreciated.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="isPaint()">
<input type="button" value="Follow" onclick="isFollow()">
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
function isPaint(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
canvas.addEventListener("mousemove", function(event) {
ctx.fillRect(event.x,event.y,10,10);
})
}
function isFollow(){
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
ctx.clearRect(0,0,500,500);
}
</script>
</body>
</html>
Work for me : http://jsfiddle.net/XF7m4/1/
Using document.getElementById("paint").onclick= function (){
PS :And think to remove the mousemouse listener ;)
To achieve what you are trying to do you will need to enhance your code a little more.
The main idea is to bind the mousemove event only once and clear the canvas if it is to behave like a follow.
Try using the following code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas</title>
</head>
<body>
<input type="button" value="Paint" onclick="CanvasPainter.paint()" />
<input type="button" value="Follow" onclick="CanvasPainter.follow()" />
<canvas id="myCanvas" width="500" height="500"></canvas>
<script type="text/javascript">
(function () {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//change draw color
ctx.fillStyle = "#FF0000";
var CanvasPainter = {
isPaint: false,
isFollow: false,
paint: function () {
this.isPaint = true;
this.isFollow = false;
return;
},
follow: function () {
this.isPaint = false;
this.isFollow = true;
return;
}
};
window.CanvasPainter = CanvasPainter;
canvas.addEventListener("mousemove", function (event) {
if (CanvasPainter.isPaint || CanvasPainter.isFollow) {
if (CanvasPainter.isFollow) {
// Clear canvas on every mousemove if it is a follow
ctx.clearRect(0, 0, 500, 500);
}
ctx.fillRect(event.x, event.y, 10, 10);
}
return;
});
return;
})();
</script>
</body>
</html>
Hope this helps!
Your isPaint() function is adding an event listener for "mousemove" to the canvas, but it isn't getting removed in the isFollow() function. If you remove your listener in the isFollow() function this should fix your problem.

Draw a canvas into another canvas not working

I am trying to draw a canvas created through javascript on another canvas. But it is not working for me,
Here is my code,
<!DOCTYPE HTML>
<html>
<head>
</script>
<script>
window.onload = function(){
var can1 = document.createElement('canvas');
can1.width = 150;
can1.height = 140;
can1.style.cssText = 'top:2px;left:2px;border:2px solid black;';
var ctx1 = can1.getContext('2d');
var img=new Image();
img.src="images/211.jpg"
ctx1.drawImage(img,0,0);
var can = document.getElementById("c");
var ctx = can.getContext('2d');
ctx.drawImage(can1,0,0);
var canvas = document.getElementById("c");
window.open(canvas.toDataURL());
}
</script>
</head>
<body >
<canvas id="c" style = "position:absolute;top:150px;width:250px;height:350px;left:500px; border:2px solid black;"></canvas>
</body>
</html>
I think the problem was that, when you were trying to drawImage that image into the canvas, image was not ready. so if u do this it works perfectly:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var imageObj = new Image();
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg";
var dynamicCanvas = document.createElement("canvas");
var dynamicContext = dynamicCanvas.getContext("2d");
dynamicCanvas .height="400";
dynamicCanvas.width="578";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
imageObj.onload = function() {
dynamicContext.drawImage(imageObj, 69, 50);
context=context.drawImage(dynamicCanvas,69,50);
window.open(canvas.toDataURL());
};
};
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>
and you can adjust the height and width of the dynamic canvas.
if you remove that window.open statement, its perfect.
but there is a problem with canvas.toDataURL()
when you try to do canvas.toDataURL() for a local file, it gives a security error (if you inspect it through google chrome) i.e.
Uncaught Error: SECURITY_ERR: DOM Exception 18
you can know more about this error : here
(see if you are getting this error). anyways, the root cause is sorted out, and there's a new problem now altogether :D..anyways better luck!!
The problem with an incorrect image display using the original code of MJQ is that he doesn't stated the size of the second canvas directly through attributes - only through style. Thus browser created a canvas of default size (300x150 for FF) and then stretched it to 250x350.
So the following modification will solve the image display:
<canvas id="c" width="250" height="350" style = "position:absolute;top:150px;width:250px;height:350px;left:500px; border:2px solid black;"></canvas>
Maybe this will help someone in the future.
what are you taking about? your code is working.
(If am getting your question correctly) I added following lines after
can1.style.cssText='border:2px solid black;';
:
var ctx1 = can1.getContext('2d');
ctx1.rect(50, 50, 500, 500);
ctx1.fillStyle = '#8ED6FF';
ctx1.fill();
and upon execution, i see a beautiful rectangle inside!!
are you using html5 supporting browser??

Categories

Resources