2013-04-02 60 views
0

我在我的HTML5代码中有一个简单的Canvas元素,并试图用外部JavaScript文件绘制它。从外部文件画布脚本

<script src="script.js" type="text/javascript"></script> 
<canvas id="can1" width="50px" height="50px"></canvas> 

//script.js: 
var can1 = document.getElementById("play"); 
var can1Context = play.getContext("2d"); 
can1Context.fillStyle="#FF0000"; 
can1Context.fillRect(0,0,150,75); 

但是这不起作用,但是如果脚本和Canvas元素在同一个文件中,它就可以工作。有人可以向我解释吗?

回答

1

将其更改为

<canvas id="play" width="50px" height="50px"></canvas> 
<!--  ^^^^ notice the different id --> 
<script src="script.js" type="text/javascript"></script> 
var can1 = document.getElementById("play"); 
var can1Context = can1.getContext("2d"); 
//    ^^^^ use the variable here, not the id! 
can1Context.fillStyle="#FF0000"; 
can1Context.fillRect(0,0,150,75); 

一个解释见Why does jQuery or a DOM method such as getElementById not find the element?

+1

他的元素和他尝试选择的元素的ID甚至不匹配,我们遇到了比我担心的更大的麻烦...... – GNi33

+0

@ GNi33:我注意到并修复了它:-)无论如何,感谢提及! – Bergi

+0

哦,对不起。我改变了这个例子的ID。我的意思是var can1 = document.getElementById(“can1”); – coldice4