问题在这里duplicate中重复。此外,没有适当的解决方案来调整画布的大小。我尝试了几种解决方案,但并没有太大帮助。我想使用JavaScript而不是css property
来调整canvas元素的大小。我有以下代码。被困在这里几天。我该如何继续前进?
export class bar {
private canvas: HTMLCanvasElement;
private ctx: CanvasRenderingContext2D;
private width_canvas: number;
private height_canvas: number;
constructor(canvas: HTMLCanvasElement) {
this.canvas = < HTMLCanvasElement > canvas;
this.ctx = < CanvasRenderingContext2D > canvas.getContext('2d');
this.width_canvas = this.canvas.width;
this.height_canvas = this.canvas.height;
if (this.width_canvas !== innerWidth || this.height_canvas !== innerHeight) {
this.width_canvas = innerWidth; // resize canvas
this.height_canvas = innerHeight;
} else {
this.ctx.clearRect(0, 0, this._w_canvas, this._h_canvas); // clear if not resized
};
window.requestAnimationFrame(() => this.draw());
};
draw() {
let wid_bar: number = this.width_canvas - 400;
this.value.forEach((val, idx) => {
// draw bar background
this.ctx.save();
this.ctx.beginPath();
this.ctx.rect(200, (idx * (80)), wid_bar, 30);
this.ctx.fillStyle = yellow;
this.ctx.fill();
window.requestAnimationFrame(() => this.draw());
};
}
答案 0 :(得分:0)
这将是JS / TS而不是css property
的另一个替代答案。
但这与窗口的宽度匹配。不是父母的宽度。
if (this.width_canvas !== innerWidth || this.height_canvas !== innerHeight) {
this.width_canvas = innerWidth; // resize canvas
this.height_canvas = innerHeight;
} else {
this.ctx.clearRect(0, 0, width, height);
};
为了匹配父div宽度。请遵循以下代码
this.canvas.width = this.parent.offsetWidth;
this.width_canvas = this.canvas.width;
this.parent = this.canvas.parentNode;
if (this.width_canvas !== this.parent.offsetWidth) {
// do whatever you need
};