javascript - 如何使绘图 Canvas 响应?

标签 javascript typescript canvas

我有一个可绘制的 Canvas 。问题是,无论何时调整大小时, Canvas 内的内容都会被剪切掉。

意思是,如果我要在中间画一些东西,然后调整到宽度的一半,那么那幅画大部分都会消失。

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

知道如何使 Canvas /绘画具有响应性吗?

最佳答案

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

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

例如重新绘制原点尺寸为originalWidth X originalHeight的图像为newWidth X 新高度:

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

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

关于javascript - 如何使绘图 Canvas 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59257750/

相关文章:

javascript - Jquery 切换以及阅读更多按钮

javascript - React 不会在 props 更新时重新渲染

node.js - 将后端部署到 azure 时遇到问题

javascript - 3d基础知识绘制魔方

Javascript 奇怪的随机行为

javascript - Fabric .js : clip everything but overlay image

Javascript 用空字符串替换特殊字符

javascript - Internet Explorer 8 JS 错误 : 'window.toolbar.visible' is null or not an object

angular - 输入变量未从模板的 @Input 属性中获取值。 Angular 5

Angular 2 (ng2) 在 [class.whatever] 中使用异步管道