html - 如何在 TypeScript 中创建矩形列表?
问题描述
如何声明矩形类型列表?
我在没有列表的情况下尝试过这种方式,但没有奏效:
在 TypeScript 文件中:
var i = 0;
var j = 0;
var index = 0;
class Rectangles {
x: number;
y: number;
height: number;
width: number;
}
let rects: Array<Rectangles>;
function Load()
{
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
rects[index].x = 25 + (j * 25);
rects[index].y = 25 + (i * 25);
rects[index].width = 25;
rects[index].height = 25;
index++;
}
}
}
function myClick() {
var canvas = <HTMLCanvasElement>document.getElementById("canvas");
let context: CanvasRenderingContext2D = canvas.getContext("2d");
i = 0;
j = 0;
index = 0;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 10; j++)
{
context.beginPath();
context.rect(rects[index].x, rects[index].y, rects[index].width, rects[index].height);
context.fillStyle = "White";
context.fill();
context.lineWidth = 2;
context.strokeStyle = "Black";
context.stroke();
index++;
}
}
}
我在 HTML 页面中调用了该函数。
所以我需要知道如何声明为一个列表。
在 c# 中,我们将这样做:
List<Rectangle> rects = new List<Rectangle>();
我怎样才能在 TypeScript 中做到这一点?
解决方案
function Load()
{
for (i = 0; i < 5; i++) {
for (j = 0; j < 10; j++) {
let rect = new Rectangle();
rect.x = 25 + (j * 25);
rect.y = 25 + (i * 25);
rect.width = 25;
rect.height = 25;
rects[index++;] = rect;
}
}
}
您在创建矩形数组方面几乎是正确的。将此数组想象成容器,并且要填充容器,您需要矩形类型。所以你必须先创建矩形,然后添加到容器中,在这种情况下是矩形。在此之前,您需要先初始化容器,如 rects = []。
推荐阅读
- python - 来自 get_queryset(self) 的 Django 排序搜索结果
- javascript - 如何随机化 EJS 变量的顺序
- node.js - Firebase Cloud Functions:触发器上的函数超时
- java - Java 将命令行参数 (args[]) 解析为 int[][] 类型
- c# - 如何将 Office Addin 从非活动状态切换为活动状态?
- c++11 - VideoCapture(0) 和 VideoCapture.open(0) 似乎不适用于 CMake (UBUNTU) (OpenCV4)
- python - 如何从本地 python 脚本调用我的 AWS Lambda 函数?
- http - 如何将文件系统制作为 http.Handler
- python - 在对数刻度上产生均匀间隔的值(如 `np.linspace()`,但在对数刻度上)
- python - TensorFlow 模型损失的近似周期性跳跃