HTML 5 canvas getElementById()返回null/undefined [英] Html 5 canvas getElementById() returns null/undefined
问题描述
这是代码:
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:
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>
在谷歌地图初始化后调用draw函数,这样DOM应该已经加载了,对吗?我可能做错了什么?
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?
推荐答案
调用draw
函数时,DOM已被加载,这是正确的.
The DOM has already been loaded when the draw
-function is called, that is correct.
但是在这之前先评估var canvas = document.getElementById('control');
行,因为它不在draw
函数中.在呈现元素之前,它会在文档的<head>
中立即执行.
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.
我建议您将init函数更改为类似的内容
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');
}
这篇关于HTML 5 canvas getElementById()返回null/undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!