在javascript数组中绘制读取值的问题 - 在HTML5画布中绘制

时间:2014-03-02 08:40:54

标签: javascript html5 canvas html5-canvas

我对这一切都比较新,我试图在html5-canvas上绘制一个基本形状。我认为一个选项是使用3.js,但我想知道是否有可能没有?每个点的x,y值都在数组中......请帮忙!下面的代码和小提琴链接:

http://jsfiddle.net/mewchew/wJwL8/8/

var canvas = document.getElementById("myCanvas");

if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    var width = canvas.width
    var height = canvas.height
    var xProp = 0.28
    var yProp = 0.43

    //Find canvas centerpoint - may need to change to global variable?
        function centerPoint(width, height) {
            x = Number(width) / 2;
            y = Number(height) / 2;
            return [x, y];
        }


    //Define diamond points
    xy = centerPoint(width,height);

    var pTx = newArray();
    pTx[0] = x;
    pTy[1] = x + xProp*x;
    pTy[2] = x;
    pTy[3] = x - xProp*x;
    pTy[4] = x;

    var pTy = newArray();
    pTy[0] = y;
    pTy[1] = y;
    pTy[2] = y - yProp*y;
    pTy[3] = y;
    pTy[4] = y + yProp*y;

    alert(String(pTx[1])+String(pTy[1]));  

    //Draw diamond
    ctx.beginPath();
    ctx.moveTo(pTx[0], pTy[0]);
    ctx.lineTo(pTx[1],pTy[1]);
    ctx.lineTo(pTx[2],pTy[2]);
    ctx.lineTo(pTx[3],pTy[3]);
    ctx.lineTo(pTx[4],pTy[4]);
    ctx.closePath();
    ctx.fillstyle() = "#FFFFFF"
    ctx.fill();


} else {
    // canvas-unsupported code here
    log('Fail');
}

1 个答案:

答案 0 :(得分:2)

您的脚本中有几处错误

<强>首先

newArray()应为new Array()

new Array()
   ^-------- see space

<强>第二

var pTx = newArray();
pTx[0] = x;                    // ---> ptx ok
pTy[1] = x + xProp*x;          // ---> its pty? why? change all to ptx
pTy[2] = x;                    // ---> change to ptx
pTy[3] = x - xProp*x;          // ---> change to ptx
pTy[4] = x;                    // ---> change to ptx

应该是

var pTx = new Array();
pTx[0] = x;
pTx[1] = x + xProp*x;
pTx[2] = x;
pTx[3] = x - xProp*x;
pTx[4] = x;

<强>第三

fillStyle不是一个属性

的方法
ctx.fillstyle() = "#FFFFFF"

应该是

ctx.fillstyle = "#FFFFFF"

Demo