gpt4 book ai didi

javascript - typescript Canvas

转载 作者:行者123 更新时间:2023-12-05 00:29:04 25 4
gpt4 key购买 nike

我正在学习 typescript ,这门课有问题,我现在的代码是

export class Window {

public title: string;
public width: number;
public height: number;
public canvas;
public ctx;

public constructor(title: string, width: number, height: number) {
this.title = title;
this.width = width;
this.height = height;
this.createCanvas();
}

public createCanvas(): void {
this.canvas = <HTMLCanvasElement>document.createElement('canvas');
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 500;
this.canvas.height = 500;

document.body.appendChild(this.canvas);
}


export class Game {

private title: string;
private width: number;
private height: number;

public constructor() {

}

window: Window = new Window("titi", 100, 100);

}
Canvas 不是这样创建的,屏幕上什么也没有出现,有人可以帮忙吗?

最佳答案

您正在初始化 Canvas ,但没有绘制它。首先,我为 canvas 添加了类型和 ctx我还为单元格大小添加了新属性

  public canvas: HTMLCanvasElement;
public ctx: CanvasRenderingContext2D;
// 20px for the size of each cell
CELL_SIZE = 20;
然后创建一个函数来绘制:
public drawWorld() {
this.ctx.beginPath();
// first draw rows
for (let x = 0; x < this.width + 1; x++) {
this.ctx.moveTo(this.CELL_SIZE * x, 0);
// this will draw the line
this.ctx.lineTo(this.CELL_SIZE * x, this.width * this.CELL_SIZE);
}
for (let y = 0; y < this.width + 1; y++) {
this.ctx.moveTo(0, this.CELL_SIZE * y);
this.ctx.lineTo(this.width * this.CELL_SIZE, this.CELL_SIZE * y);
}

this.ctx.stroke();
}
然后创建一个实例并调用方法:
const w = new Window("canvas", 12, 12);
w.drawWorld();
这是完整的代码:
export class Window {
public title: string;
public width: number;
public height: number;
public canvas: HTMLCanvasElement;
public ctx: CanvasRenderingContext2D;
// 20px for the size of each cell
CELL_SIZE = 20;

public constructor(title: string, width: number, height: number) {
this.title = title;
this.width = width;
this.height = height;
this.createCanvas();
}

public createCanvas(): void {
this.canvas = <HTMLCanvasElement>document.createElement("canvas");
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 500;
this.canvas.height = 500;
document.body.appendChild(this.canvas);
}

public drawWorld() {
this.ctx.beginPath();
// first draw rows
for (let x = 0; x < this.width + 1; x++) {
this.ctx.moveTo(this.CELL_SIZE * x, 0);
// this will draw the line
this.ctx.lineTo(this.CELL_SIZE * x, this.width * this.CELL_SIZE);
}
for (let y = 0; y < this.width + 1; y++) {
this.ctx.moveTo(0, this.CELL_SIZE * y);
this.ctx.lineTo(this.width * this.CELL_SIZE, this.CELL_SIZE * y);
}

this.ctx.stroke();
}
}

const w = new Window("canvas", 12, 12);
w.drawWorld();
这是工作证明:
enter image description here

关于javascript - typescript Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com