2014-03-02 60 views
0

我對這一切都比較陌生,並且試圖在html5畫布上繪製基本形狀。我認爲一個選項是使用3.js,但我想知道是否可以不使用它?每個點的x,y值都在數組中...請幫忙!下面的代碼和小提琴鏈接:在javascript數組中繪製讀取值的問題 - 在HTML5畫布中繪圖

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'); 
} 

回答

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