如何在JS中将矩形设置为数组的对象

How to set rectangles as objects to array in JS?

本文关键字:设置 数组 对象 JS      更新时间:2023-09-26

我是一个初学者。我想创建一个像素艺术网站。为此,我尝试开发我的javascript代码。现在,我正在通过使用var作为对象和数组设置不同的矩形来简化代码,以避免键入数百万行。我认为在第二部分创建一个数组构造函数,为2D数组中的每个矩形定义坐标(其他x,其他y)。目前,我不明白为什么代码的第一部分不起作用。你能建议一下你的想法吗?提前非常感谢。这是我的代码(JS Bin上的链接):

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); 
  }
}
 for (var j=0; j<r.length; i++){
 r[j]=ctx.moveTo(x+w*j,y+h*j); 
 }

您在使用字母"j"时键入了"i++"。不确定这是否解决了问题。

你为什么在中使用Math.abs

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

将"var w"设置为10不是更容易吗?

var w = 10;

您想要的是如何创建类并从该类生成对象?

如果是这样,这就是创建类和生成对象的方式。

//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());
}