使用window事件调整画布元素的大小 [英] canvas element resizing using window event
问题描述
我正在使用打字稿来绘制画布元素。我想使我的canvas元素响应屏幕尺寸。这样我可以将画布大小与父div元素匹配。
I am using typescript to draw canvas element. I would like to make my canvas element responsive to the screen size. So that I can match the canvas size to the parent div element.
我尝试使用此删除画布中的大小并将其提供给.css 。但这无济于事,因为我有两个固定的要素。我发现此解决方案已有8年的历史了画布调整大小。
I have tried to use this removing the size in canvas and providing it in .css. But this doesn't help because I have two fixed elements. I have found this solution which is 8 years old canvas resize.
我该如何解决这个问题?我发布的答案严重扭曲了图像质量。还有其他方法吗?
How can I approach this problem ? The answer which I have posted distortes the image quality way too much. Is there any other approach ?
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;
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());
};
}
<div class="bar">
<canvas id="canvas" width="1200" height="200"> This does not work </canvas>
</div>
推荐答案
尝试(如果仅使用CSS宽度而不重绘,则图片质量会下降),而不是输入Balue读取屏幕尺寸
try (if you use css width only without redrawing then picture it will loose quality) instead input balue read screen size
function change(inp) {
can.width = inp.value;
can.height = inp.value/4;
draw(can, [5,10,15,20])
}
function draw(canvas,value) {
let ctx = can.getContext('2d');
let wid_bar = canvas.width - 400;
value.forEach((val, idx) => {
// draw bar background
ctx.save();
ctx.beginPath();
ctx.rect(200, idx * 80, wid_bar, 30);
ctx.fillStyle = 'yellow';
ctx.fill();
});
}
change(audio);
canvas { background: black; }
<input id="audio" type="range" min="100" max="600" oninput="change(this)" value=150 /><br>
<canvas id="can"></canvas>
这篇关于使用window事件调整画布元素的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!