+ 3
Canvas is not working
I have two page here and I think they are equal. But why error in canvas is occuring? https://code.sololearn.com/WwAh4d1Q9VAK/?ref=app https://code.sololearn.com/W6356CNUJz70/?ref=app
2 Answers
+ 8
The way the editor places the script your Javascript code loads before your doc in the 2nd one. delay it with onload or similar event, it should work fine.
this.onload =function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillRect(25, 25, 100, 100);
}
+ 7
In your second code, the script run before loading the document so the script doesn't find your canvas element and code throws error.
so you need an event handler like onload or delay the executing of script by setTimeout method.
you can write it like..
window.onload=function (){ your code here };
or
setTimeout (function (){your code here}, time);
Where time is milliseconds like 200.