2016-07-23 35 views
1

我是一個開始。我想創建一個像素藝術網站。爲此,我嘗試開發我的JavaScript代碼。現在我正在通過使用var作爲對象和數組來設置不同的矩形來簡化代碼,以避免鍵入數行代碼。比我想在第二部分創建一個數組構造函數,爲二維數組中的每個矩形定義座標(其他x,其他y)。 目前我不知道爲什麼代碼的第一部分不起作用。你能提出你的想法嗎?提前致謝。 這裏是我的代碼(link on JS Bin):如何將矩形設置爲JS中的數組對象?

var canvas; 
var ctx; 
var x = 0; 
var y = 0; 
var w = 10; // Width=10px 
var h = w; // Heigth=10px 

function init() { 
canvas = document.querySelector('#myCanvas'); 
ctx = canvas.getContext('2d'); 
draw(); 
} 

// Create a rect by path method for restoring the buffer 
var rect; 
function draw(){ 
    ctx.beginPath(); 
    ctx.rect(x,y,w,h); 
} 

var c = ['#66757F', '#F7F7F7', '#CCD6DD']; // Setting a color palette as an array 
    for (var i=0; i<c.length; i++){ 
    c[i]=ctx.fillStyle(); 
    } 

// Define colored rectangles as the Objects 
var r1 = {rect;[0]} 
var r2 = {rect;[1]} 
var r3 = {rect;[2]} 
ctx.fill(); 

// Setting three rectangle by diagonal 
var r=[r1,r2,r3];// Array of setted rectangles 
function draw(){ 
    for (var j=0; j<r.length; j++){ 
    r[j]=ctx.moveTo(x+w*j,y+h*j); 
    } 
} 

回答

1
for (var j=0; j<r.length; i++){ 
r[j]=ctx.moveTo(x+w*j,y+h*j); 
} 

你鍵入'我++使用字母時, 'J'。 不確定這是否解決了問題。

爲什麼使用Math.abs在

var w = Math.abs(-10); // Width=10px 

是不是很容易就能設置 '變種W' 到10?

var w = 10; 
+0

謝謝Krandalf,我確實犯了錯誤,並輸入了你的建議更改,但代碼仍然不起作用。我想問題是var r1 = {rect; [0]},因爲填充方法看不到數組 –

1

你正在尋找如何創建類和從該類中創建對象?

如果是這樣,您將如何創建一個類並創建對象。

//This will hold all of your objects. 
var listOfObjects = []; 

//This is a class. You can create objects with it. 
function myClass() { 

    //location 
    this.X = 0; 
    this.Y = 0; 

    //size 
    this.width = 5; 
    this.height = 5; 

} 

function CreateNewObject() { 

    //This will create and add an object of myClass to your array. 
    //Now you can loop through the array and modify the values as you wish. 
    listOfObjects.push(new myClass()); 

} 
+0

中設置的顏色謝謝@DanielDees,因爲我沒有使用類構造函數創建對象/數組的經驗這一刻我只是通過實現Object.defineProperty:[link](https://jsbin.com/?html,js,output)來實現更改後的代碼,但它仍然不起作用。 –

相關問題