0

I have a simple Canvas element in my HTML5 Code and trying to draw in it with a external javascript file.

<script src="script.js" type="text/javascript"></script>
<canvas id="can1" width="50px" height="50px"></canvas>

//script.js:
var can1 = document.getElementById("play");
var can1Context = play.getContext("2d");
can1Context.fillStyle="#FF0000";
can1Context.fillRect(0,0,150,75);

But this is not working, but if the script is in the same file as the Canvas Element, it works. Can somebody explain that to me?

coldice4
  • 51
  • 2
  • 7

1 Answers1

1

Change it to

<canvas id="play" width="50px" height="50px"></canvas>
<!--        ^^^^ notice the different id -->
<script src="script.js" type="text/javascript"></script>
var can1 = document.getElementById("play");
var can1Context = can1.getContext("2d");
//                ^^^^ use the variable here, not the id!
can1Context.fillStyle="#FF0000";
can1Context.fillRect(0,0,150,75);

See Why does jQuery or a DOM method such as getElementById not find the element? for an explanation.

Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164