简体   繁体   English

如何缩放HTML画布中的图形并将其复制到另一个画布?

[英]How can I scale a drawing from an HTML canvas and copy it to another canvas?

If I draw something on my canvas I would like to press save and then on save scale the image of the drawing to fit a smaller canvas in another part of the page. 如果我在画布上绘制某些内容,我想按保存,然后按保存比例按比例绘制图像,以使较小的画布适合页面的另一部分。 I think it would have something to do with the base64 src of the drawing but I'm not entirely sure how it could be done. 我认为这可能与图形的base64 src有关,但我不完全确定该怎么做。

Suppose if the original canvas I drew on was 600px by 400px and the smaller canvas was 300px by 150px when what would the code look like? 假设我画的原始画布是600px x 400px,较小的画布是300px x 150px,那么代码是什么样的?

Since the two canvases have different aspect ratios, I would use the following syntax: 由于两个画布的纵横比不同,因此我将使用以下语法:

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

In this cases sx , sy , sWidth and sHeight specify which part of the original canvas should be copied, while dx , dy , dWidth and dHeight specify which part of the canvas they should be rendered on. 在这种情况下, sxsysWidthsHeight指定应复制原始画布的哪一部分,而dxdydWidthdHeight指定应在画布的哪一部分上进行渲染。

 const canvas1 = document.getElementById("c"); const ctx1 = canvas1.getContext("2d"); ctx1.beginPath() ctx1.arc(125,125,100,0,2*Math.PI); ctx1.stroke() const canvas2 = document.getElementById("c1"); const ctx2 = canvas2.getContext("2d"); ctx2.drawImage(canvas1,0,0,600,400,0,0,300,150); 
 canvas{border:1px solid} 
 <canvas id="c" width="600" height="400"></canvas> <canvas id="c1" width="300" height="150"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM