gpt4 book ai didi

javascript - 如何使绘图 Canvas 响应?

转载 作者:行者123 更新时间:2023-11-30 06:10:20 25 4
gpt4 key购买 nike

我有一个可绘制的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com