【问题标题】:responsive canvas element with typescript带有打字稿的响应式画布元素
【发布时间】:2019-05-09 14:38:04
【问题描述】:

这里有重复的问题duplicate。此外,画布调整大小没有适当的解决方案。我尝试了一些没有太大帮助的解决方案。我想用 JavaScript 而不是css property 调整画布元素的大小。我有以下代码。被困在这里好几天了。我该如何继续前进?

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());
        };
      }

【问题讨论】:

  • 如果你已经问过同样的问题,为什么还要问呢?此外,您根本没有解释代码的哪一部分给您带来麻烦或无法按预期工作。
  • @Esko 我没有得到答案,也忘了提及打字稿。没有错误也没有变化。如果我调整屏幕大小,画布元素保持不变。
  • @Esko 对于这个问题,目前还没有合适的解决方案。所以我想发布它以获得更多关注
  • @Cerberus 即使我已经提到过。

标签: html typescript canvas


【解决方案1】:

这将是 JS/TS 的另一个替代答案,而不是 css property。 但这与 thw 窗口的宽度相匹配。不是父宽度。

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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多