3

here's the code:

HTML:

<body onload="initializeMap()">
    <div id="map_canvas" style="width:100%; height:100%; z-index:1"></div>
    <canvas id="control" style="width:100%; height:100%; z-index:2">Does Not Support Canvas Element</canvas>
</body>

Javascript:

<script type="text/javascript">
    var canvas = document.getElementById('control');
    var context = canvas.getContext('2d');

    function draw(){
        context.font = "bold 12px sans-serif";
        context.fillText("x", 248, 43);
    }
</script>

the draw function is called after initialization of the google map so the DOM should have already loaded by then, correct? What might have I done incorrectly?

Bahamut
  • 1,929
  • 8
  • 29
  • 51
  • 1
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – CertainPerformance May 30 '19 at 07:24

2 Answers2

6

The DOM has already been loaded when the draw-function is called, that is correct.

But the var canvas = document.getElementById('control');-line is evaluated before that, because it is not in the draw-function. It is executed immediately in the <head> of the document BEFORE the elements have been rendered.

I would suggest you change your init function to something like that

var canvas,context;
function initializeMap() {
   canvas = document.getElementById('control');
   context = canvas.getContext('2d');
}
Michael Sandino
  • 1,818
  • 1
  • 13
  • 10
3

If your javascript is loaded prior to your body then canvas will be undefined because the browser hasn't loaded/rendered it yet.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • It's on the tag but the function is called . Shouldn't it work normally? any examples? – Bahamut Sep 13 '11 at 04:30
  • I don't see a function, I set a variable setter `var canvas = doucment.get...('control');` There is no document when the browser runs javascript in the head. – Erik Philips Sep 13 '11 at 05:27
  • the javascript is declared on the but the function draw() is called after the document is loaded which would be fine. – Bahamut Sep 13 '11 at 06:45