【问题标题】:Unable to resize canvas无法调整画布大小
【发布时间】:2019-10-23 18:46:31
【问题描述】:

我想加载图像并根据图像尺寸调整画布大小。

目前,代码如下:

canvas = null;
  maxWidth = 800;
  canvasWidth = 200;
  canvasHeight = 200;

  constructor() { }

  loadImage(src) {
    return new Promise((resolve, reject)=> {
      console.log(src);

      var img = new Image();
      img.onload = () => resolve(img);
      img.src = src;
    });
  }


  ngOnInit() {
    var src = "example_image_url";
    this.canvas = document.getElementById('stage');
    let ctx = this.canvas.getContext("2d");
    this.loadImage(src).then(img => {
      let width = img.width;
      let height = img.height;
      if (width > this.maxWidth) {
        const scalingFactor = width / this.maxWidth;
        width = this.maxWidth;
        height /= scalingFactor;
        this.canvasWidth = width;
        this.canvasHeight = height;
      }
      ctx.drawImage(img,0,0, this.canvasWidth, this.canvasHeight);
    });
}

画布定义如下:

<canvas id="stage" [width]="canvasWidth" [height]="canvasHeight"></canvas>

加载图像时,它是不可见的。如果 canvasWidth 和 canvasHeight 不变,则显示图像。有谁知道如何正确加载图像并重新调整画布大小?

【问题讨论】:

  • 我不会说它是重复的,因为建议的答案与 javascript 有关。我不确定这是特定于角度的问题还是由其他原因引起的。

标签: angular


【解决方案1】:

不幸的是,您无法将 Width 和 Height 绑定到画布,因为在您的画布被渲染后,即使更改 this.canvasWidththis.canvasHeight 它也不会对画布产生影响,因为您的角度范围上有 ctx 元素您可以访问画布并更改它的值,它将呈现您的图像

if (width > this.maxWidth) {
    const scalingFactor = width / this.maxWidth;
    width = this.maxWidth;
    height /= scalingFactor;
    ctx.canvas.width = width;
    ctx.canvas.height = height;
}
ctx.drawImage(img,0,0, ctx.canvas.width, ctx.canvas.height);

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-06
    • 2011-03-14
    • 2013-12-15
    • 2013-11-19
    • 2014-11-04
    相关资源
    最近更新 更多