使用window事件调整画布元素的大小

时间:2019-05-06 07:29:46

标签: javascript html typescript canvas

我正在使用打字稿来绘制画布元素。我想使我的canvas元素响应屏幕尺寸。这样我就可以将画布大小与父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>

1 个答案:

答案 0 :(得分:1)

尝试(如果仅使用css宽度而不重绘,那么图片会降低质量),而不是输入Balue读取屏幕尺寸

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>