📜  从数组创建许多项目到画布 - Javascript (1)

📅  最后修改于: 2023-12-03 14:49:25.385000             🧑  作者: Mango

从数组创建许多项目到画布 - JavaScript

在JavaScript中,我们可以使用数组来处理大量的数据,比如将一组数据渲染到画布上。本文将介绍如何从数组中创建多个项目并将它们绘制到画布上。

创建画布

使用HTML中的canvas元素来创建画布,我们可以通过JavaScript获取canvas元素并设置它的宽高,然后使其可见。

<canvas id="canvas"></canvas>

const canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 400;
canvas.style.display = "block";
创建项目

我们可以使用JavaScript中的类来创建一个项目对象,并设置它的参数,如位置、大小、颜色等。

class Item {
  constructor(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height
    this.color = color;
  }
  draw(ctx) {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}
创建数组

我们可以使用JavaScript中的数组来批量创建项目对象,并存储到数组中。

const items = [];
for(let i=0; i<10; i++) {
  const item = new Item(i*50, 50, 40, 40, "blue");
  items.push(item);
}
绘制项目

使用canvas的API来绘制项目,我们可以遍历数组中的每个项目,并将它们绘制到画布上。

const ctx = canvas.getContext("2d");
items.forEach(item => {
  item.draw(ctx);
});

现在,就可以看到在画布上绘制出了10个蓝色方块。完整的代码示例如下:

<canvas id="canvas"></canvas>

const canvas = document.getElementById("canvas");
canvas.width = 600;
canvas.height = 400;
canvas.style.display = "block";

class Item {
  constructor(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height
    this.color = color;
  }
  draw(ctx) {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

const items = [];
for(let i=0; i<10; i++) {
  const item = new Item(i*50, 50, 40, 40, "blue");
  items.push(item);
}

const ctx = canvas.getContext("2d");
items.forEach(item => {
  item.draw(ctx);
});

结果如下:

canvas

以上就是如何从数组创建许多项目并将它们绘制到画布上的简介。