簡體   English   中英

使用窗口事件調整畫布元素大小

[英]canvas element resizing using window event

我正在使用打字稿來繪制畫布元素。 我想讓我的畫布元素響應屏幕尺寸。 這樣我就可以將畫布大小與父 div 元素匹配。

我嘗試使用它來刪除畫布中的大小並在 .css 中提供它 但這無濟於事,因為我有兩個固定元素。 我找到了這個解決方案,它是 8 歲的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM