我在画布画中做错了什么?

时间:2014-01-19 06:18:33

标签: javascript html5 canvas

我是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>

1 个答案:

答案 0 :(得分:3)

您的值是NaN(非数字)。改变这些行:

var HEIGHT = ctx.height;
var WIDTH = ctx.width;

var HEIGHT = c.height;
var WIDTH = c.width;

你得到合适的号码。但是,您的y值位于画布区域之外 - 如果您使用console.log值,则会看到此值。一般来说,数学似乎存在一些问题,我在这里没有提到,但与画布有关,你应该更进一步。