簡體   English   中英

如何使繪圖畫布響應?

[英]How to make a drawing canvas responsive?

我有一個可繪制的畫布。 問題是,無論何時調整大小,畫布內的內容都會被剪掉。

意思是,如果我在中間畫一些東西,然后將其調整為寬度的一半,那么該圖大部分都會消失。

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

我想要的結果:

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

這是我的 Canvas 的構建方式:

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

用於調整大小的主機偵聽器:

  @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");
  }

知道如何使畫布/繪畫具有響應性嗎?

您可以使用drawImage函數的swidthsheightdwidthdheight屬性來縮放畫布圖像而不更改它。 s -prefixed 參數是指原始圖像, d -prefixed 參數是指新圖像。 此外,(根據我的經驗)在指定這些屬性時,您還需要指定其他可選參數,以便它知道從哪里開始捕獲/繪制圖像。

這應該是您所需要的,因為調整畫布大小也可以被認為是縮放圖像。

例如,將原點大小為originalWidth X originalHeight的圖像重新繪制為newWidth 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);

注意:您可能還需要更改捕獲方法以確保在畫布調整大小后原始圖像不會丟失。 如果您的原始方法有效,您不必擔心這一點,但我想我會添加它以保持完整性。

暫無
暫無

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

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