Javascript 如何使绘图画布具有响应性?
我有一块可画的帆布。问题是,无论何时调整大小,画布中的内容都会被剪切掉 意思是,如果我在中间画东西,然后调整到宽度的一半,那么画图就会消失。Javascript 如何使绘图画布具有响应性?,javascript,typescript,canvas,Javascript,Typescript,Canvas,我有一块可画的帆布。问题是,无论何时调整大小,画布中的内容都会被剪切掉 意思是,如果我在中间画东西,然后调整到宽度的一半,那么画图就会消失。 _________________ _________ | | | | | o o | | o | | o | >> | o| | ----- | |
_________________ _________
| | | |
| o o | | o |
| o | >> | o|
| ----- | | ---|
|________________| |________|
我想要的结果是:
________ ____________
| | | o o |
| o o | | o |
| o | OR |___-----___|
| --- |
|_______|
这就是我的画布的构建方式:
<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");
}
@HostListener('window:resize',['$event'])onResize(e){
this.canvasWidth=window.innerWidth;
this.canvasHeight=window.innerHeight;
//不好的解决方案,但在画作因大小调整而消失后重新绘制画布。
设置超时(()=>{
this.ctx.drawImage(this.canvas,0,0);
}, 1);
}
ngAfterViewInit(){
this.canvas=document.getElementById('myCanvas');
this.ctx=this.canvas.getContext(“2d”);
}
您知道如何使画布/绘画响应吗?您可以使用函数的
swidth
、sheight
、dwidth
和dheight
属性来缩放画布图像,而无需更改。带s
前缀的参数表示原始图像,带d
前缀的参数表示新图像。另外,(根据我的经验),在指定这些属性时,还需要指定其他可选参数,以便它知道从何处开始捕获/绘制图像
这应该是您所需要的,因为调整画布的大小也可以被认为是缩放图像
例如,在原始尺寸为originalWidth
XoriginalHeight
的原点重新绘制图像,使其成为newWidth
XnewHeight
:
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);
注意:您可能还需要更改捕获方法,以确保在调整画布大小后不会丢失原始图像。如果你原来的方法有效的话,你不必担心这个问题,但是为了完整性,我想我应该添加它