0
我是JavaScript新手,所以很抱歉,如果我的错误是明显的!我正在尝试使用规范形式方程绘制椭圆。我在画布上画错了什么?
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;">
</canvas>
<script language="javaScript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var HEIGHT = ctx.height;
var WIDTH = ctx.width;
function transform(p){
return [ WIDTH/2 + p[0], HEIGHT/2 - p[1]];
}
var a = 70; //length parallel to x axis
var b = 30; //length parallel to y axis
var h = 150 - WIDTH/2; //when tranformed this gives the pixel 150
var k = -HEIGHT/2 - 100; //when transformed this gives pixel 100
function y(x){
return b*Math.sqrt(1 - Math.pow((x - h)/a, 2)) + k;
}
var dx = a/2/100 ; //each quadrant is broken into 100 segments
var pOld = [h - a/2, k]; //starting point
var pNew = [0,0];
var x1 = 0;
var x2 = 0;
var y1 = 0;
var y2 = 0;
var temp = [0,0];
for (var i = 0; i < 100; ++i){
pNew[0] = pOld[0] + dx;
pNew[1] = y(pNew[0]);
temp = transform(pOld);
x1 = temp[0]; y1 = temp[1];
temp = transform(pNew);
x2 = temp[0]; y2 = temp[1];
ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); //x1, y1 -> x2, y2
ctx.moveTo(x1, -y1); ctx.lineTo(x2, -y2); //x1,-y1 -> x2,-y2
ctx.moveTo(-x1, y1); ctx.lineTo(-x2, y2); //-x1,y1 -> -x2, y2
ctx.moveTo(-x1, -y1); ctx.lineTo(-x2, -y2); //-x1,-y1 -> -x2,-y2
pOld = pNew;
}
ctx.lineWidth = 2;
ctx.strokeStyle = "#232323";
ctx.stroke();
</script>
</body>
</html>
那么当你运行该代码时会发生什么?我的猜测是你会得到一个错误,因为你试图在解析之前访问canvas元素。尝试将脚本元素移动到主体的末尾(画布之后)。还有'[x1,y1] = transform(pOld);'解构赋值在所有浏览器中都不起作用。 – nnnnnn
你检查了控制台还是尝试调试?应该有一些未定义的变量错误。在'transform'function – z33m
@nnnnnn和z33m:“javascript to new”中应该是'p [0]'而不是'p1 [0]'可能意味着Broseph不知道开发工具。 Broseph:目前大多数浏览器都内置了调试工具,这将有助于指出您的javascript错误发生的位置。看看这个介绍(它过时了,但仍然是一个很好的介绍):http://www.html5rocks.com/en/tutorials/developertools/part1/ – markE