的HTML文件中被調用我的代碼有一個球在畫布上跳動,我在HTML中創建hte畫布,球代碼在.js文件中。當我運行html文件時,球代碼不起作用,但是當我在html文件中的標籤之間放置球代碼時,它確實起作用。任何人都可以看到它在.js文件中不起作用的原因嗎?Javascript文件在
下面是HTML文件:
<html>
<header>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bouncing Ball Paint</title>
<body>
Welcome to Paint Brush!
Before you begin: Please type in a color, width, and speed. Now sit back and enjoy the show.</body>
<body>
<style>
#ball{background:#CCC;}
</style>
</header>
<body style="background-color:#FFDEAD;">
Ball Width: <input type="text" id="lineWidth"></input>
Ball Color: <input type="text" id="lineColor"></input>
Ball Speed X:<input type="text" id="speedx"></input>
<input type="button" value="Clear" onClick="window.location.href=window.location.href">
<input type="button" value="Green" id="green" onclick= "DGN.GreenRect()" />
<div id="container">
<canvas id="ball" width="1000" height="700"></canvas>
<script type="text/javascript"
src="balledit3.js"> </script>
</body>
</html>
這裏是我想有一個.js文件,但在HTML標記之間將工作代碼:
var x=50;
var y=300;
var dx=10;
var dy=10;
function draw(){
var canvas = document.getElementById('ball');
context= ball.getContext('2d');
context.clearRect(0,0,canvas.width,canvas.height);
lineColor = (document.getElementById('lineColor').value.length>0)?document.getElementById('lineColor').value:'#0000FF';
lineWidth = (document.getElementById('lineWidth').value.length>0)?document.getElementById('lineWidth').value:'10';
context.beginPath();
context.fillStyle=lineColor;
context.arc(x,y,lineWidth,20,Math.PI*2,true);
context.closePath();
if (lineWidth){
context.lineWidth=lineWidth;
}
if (lineColor){
context.strokeStyle=lineColor;
context.stroke();
}
context.fill();
if(x<0 || x>1000)
dx=-dx;
if(y<0 || y>700)
dy=-dy;
x+=dx;
y+=dy;
fr = (document.getElementById('speedx').value>0)?document.getElementById('speedx').value:50;
setTimeout(draw,fr);
}
draw();
您的HTML代碼有一些嚴重的問題。考慮[驗證你的代碼](http://validator.w3.org),看看它是否能解決你的問題。 – Quantastical 2012-08-09 20:09:40
如果不是 - 如果您檢查javascript錯誤控制檯,會得到什麼樣的錯誤? – 2012-08-09 20:11:04
標題中有兩個額外的主體標籤,其中一個是文字,一個是未封閉的,不應該在那裏。一個HTML文檔只能得到一個頭文件和一個主體。 – 2012-08-09 20:12:59