0
Canvas help please...
var mydr=document.getElementById("dr"); var ctx=mydr.getContext("2d"); ctx.moveTo(0,0); ctx.lineTo(200,100); ctx.stroke(); its execution, saying cannot read getContext property.....what the mistake am I making?
5 Respostas
+ 6
Real good answrer:
Scripts putted before element they want to access should only work if waiting for document load end (scripts are ran as soon as they are parsed, in order of apparition in Html code). The advised solution is to differ execution requiring DOM access after end of loading, using 'window.onload' event (lazy solution relatively unadvised) or 'DOMContentLoaded' event of 'document' object (window and document are available in DOM as soon as Html start to be parsed because they are the root elements of any web content):
window.onload = function() {
/* initializations requiring DOM access */
};
// a few less lazy (and better practice):
window.addEventListener('load', function() { /* init */ });
// a little more efficient:
window.addEventListener('DOMContentLoaded', function() { /* init */ });
... Last one will be fired a bit sooner than 'onload' in case of heavy linked ressources in content page, as 'onload' wait for all linked file load are completly done, while 'DOMContentLoaded' will only wait for root Html code to be completly parsed (even if linked ressources aren't still loaded).
In any case, you can use function names (references) in place of inlined declaration of anonymized ones:
function init() { /* init code */ }
window.onload = init;
window.addEventListener('load',init);
window.addEventListener('DOMContentLoaded',init);
(don't do really that: you will run your init() function three times :P)
Anyway, advantage of using addEventListener() method are:
+ doesn't overwrite previous assignement (contrarly to event html attribute)
+ handle events not available as html attributes
Disadvantage:
- less shorthanded :P
+ 2
to all those solo learner, who starting with canvas elements, please put ur canvas related JavaScript, after canvas element, not before it, otherwise , u will get same error,
cannot read getContext property of null.
+ 1
I mean JavaScript related with canvas, should be put after canvas element..
0
Could you please show your html? Maybe the error is a mistype in the canvas tag.
0
thanks, but I realized my mistake, I put up my script, before HTML canvas element....so script was not working....thanx again , u only one who replied.....