0

I wanted to do a canvas and a line but the JavaScript console says: “null is not an object (evaluating ‘c.getContext’)”.

// HTML code:

<!DOCTYPE html>
<html>
<head>
<script src="provaCanvas.js" type="text/javascript"></script>
</head>
<body>
<canvas id="canvas-id" width="200" height="100"
style="border: solid 1px  black;"></canvas>
</body>
</html>


// JavaScript code:

var c = document.getElementById("canvas-id");
var ctx = c.getContext('2d')
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();

j08691
  • 190,436
  • 28
  • 232
  • 252
  • 1
    Have you read or try [this solution](https://stackoverflow.com/a/47457691/5454578)? – andres Sep 04 '20 at 18:54
  • Does this answer your question? [Javascript Error Null is not an Object](https://stackoverflow.com/questions/14207922/javascript-error-null-is-not-an-object) – flori4nk Sep 04 '20 at 18:55
  • Hi Mattia and welcome to SO. If you are new here then please take the [tour](https://stackoverflow.com/tour). See the [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) section on how to improve your question. Try to describe the problem in your question instead of asking for help, we'll make sure to help you. Look into [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) to see how you can make an interactive version of your code for us to check out. This way we can experience what you're experiencing. Good luck! – Emiel Zuurbier Sep 04 '20 at 19:04
  • ```document.addEventListener('DOMContentLoaded', function() { var c = document.getElementById("canvas-id"); if( typeof c != 'undefined' || c != null ){ var ctx = c.getContext('2d') ctx.moveTo(0,0); ctx.lineTo(200,100); ctx.stroke(); } });``` – Rayees AC Sep 04 '20 at 19:08
  • `typeof c != 'undefined' || c != null` check the value of c not null and undefined And load in `document.addEventListener('DOMContentLoaded', function() {}` – Rayees AC Sep 04 '20 at 19:09

1 Answers1

0

Try moving that script tag to somewhere below your canvas tag.

Why this works:
I'm guessing the Javascript code you've provided is what's being called by <script src="provaCanvas.js" type="text/javascript"></script>. The problem is that your script is looking for that canvas element BEFORE that canvas element has loaded.

Benjamin C
  • 301
  • 1
  • 7