如何使绘图画布响应?

时间:2019-12-09 22:45:18

标签: javascript typescript canvas

我有一个可绘制的画布。问题是,每当您调整大小时,画布中的内容都会被剪切掉。

意思是,如果我要在中间画一些东西,然后将其尺寸调整为宽度的一半,则该画图将大部分消失。

_________________       _________
|                |      |        | 
|     o   o      |      |     o  |
|       o        |  >>  |       o|     
|     -----      |      |     ---|
|________________|      |________|

我想要的结果

________      ____________
|       |     |   o   o   |
| o   o |     |     o     |
|   o   | OR  |___-----___|
|  ---  |     
|_______|    

这是我的Canvas的构建方式:

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

用于调整大小的Hostlistener:

  @HostListener('window:resize', ['$event']) onResize(e) {

    this.canvasWidth = window.innerWidth;
    this.canvasHeight = window.innerHeight;

    //Bad solution, but redrawing the canvas after the painting disappears due resizing.
    setTimeout(() => {
      this.ctx.drawImage(this.canvas, 0, 0);
    }, 1);
  }


 ngAfterViewInit() {
    this.canvas = <HTMLCanvasElement>document.getElementById('myCanvas');
    this.ctx = this.canvas.getContext("2d");
  }

关于如何使画布/绘画具有响应性的任何想法?

1 个答案:

答案 0 :(得分:0)

您可以使用drawImage函数的swidthsheightdwidthdheight属性来缩放画布图像而不更改它。 s前缀的参数是指原始图像,而d前缀的参数是指新图像。另外,(以我的经验)在指定这些属性时,还需要指定其他可选参数,以便它知道从哪里开始捕获/绘制图像。

这应该是您所需要的,因为调整画布的大小也可以认为是缩放图像。

例如,以原尺寸为originalWidth X originalHeightnewWidth X newHeight的原点重新绘制图像:

this.ctx.drawImage(this.canvas,
                   0, // sx, set this if the original image is offset from the origin
                   0, // sy, set this if the original image is offset from the origin
                   originalWidth, 
                   originalHeight,
                   0, // dx, set this if you want the image to be offset from the origin
                   0, // dy, set this if you want the image to be offset from the origin
                   newWidth, 
                   newHeight);

注意:您可能还需要更改捕获方法,以确保在调整画布大小后不会丢失原始图像。如果您的原始方法可行,则不必担心此事,但我想我会添加它以确保完整性。