我正在使用打字稿来绘制画布元素。我想让我的画布元素响应屏幕尺寸。这样我就可以将画布大小与父 div 元素相匹配。
我试过用这个删除画布中的大小并在 .css 中提供它。但这没有帮助,因为我有两个固定元素。我找到了这个已有 8 年历史的解决方案画布调整大小 https://stackoverflow.com/questions/5825447/javascript-event-for-canvas-resize.
我该如何解决这个问题?我发布的答案过度扭曲了图像质量。还有其他办法吗?
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 宽度而不重绘,那么图片将失去质量)而不是输入值读取屏幕尺寸
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)