If var raster = document.querySelector ("canvas") is in the HTML file, raster is defined and declared. However, I'd like to have everything in my js file, only function calls in my HTML. When I try putting var raster... in the .js file, it keeps coming up null.
Is there any way to have document.querySelector point to the associated HTML file?
// this doesn't work
//var raster = document.querySelector ("canvas").getContext ("2d");
function drawSquare (w,h) {
raster.fillStyle = "blue";
raster.fillRect (0,0,w,h);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IFS</title>
<script src="IFS.js"></script>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script>var raster = document.querySelector ("canvas").getContext ("2d");
drawSquare (500,500);</script>
</body>
</html>
Try moving <script src="IFS.js"></script> to the end of the HTML code, before the closing <body> tag, instead of having it at the <head>.
The issue is caused because the script is loaded before the <canvas> is rendered, so document.querySelector ("canvas") returns null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With