简体   繁体   English

Canvas 高质量绘制图像 - Javascript

[英]Canvas drawImage with high quality - Javascript

I'm using konva.js to draw elements on an HTML Canvas.我正在使用 konva.js 在 HTML Canvas 上绘制元素。 When the user finishes its design in the canvas, the creation can be exported into a PDF file.当用户在 canvas 中完成设计后,可以将创建导出到 PDF 文件中。 In this context, my HTML structure is the following:在这种情况下,我的 HTML 结构如下:

  • a div "canvas" to append all the canvas一个 div“画布”到 append 所有 canvas
  • a div "canvas0/canvas1" and so on to append each konva-canvas一个 div "canvas0/canvas1" 等等到 append 每个 konva-canvas
  • an auto-generated div "konvajs-content"一个自动生成的 div “konvajs-content”
  • and finally, multiple canvases depending on the number of layers最后,多个画布取决于层数

So, to export the PDF I have to go through each div "canvas + number" and then go through each canvas childNodes to use the getContext('2d') and drawImage function to draw an Image with the contents of each canvas (hopefully this description is not too confusing...). So, to export the PDF I have to go through each div "canvas + number" and then go through each canvas childNodes to use the getContext('2d') and drawImage function to draw an Image with the contents of each canvas (hopefully this描述不是太混乱......)。

Well, I'm able to export the pdf with multiple pages according to the number of canvases drawn, but the image drawn from the canvas has very low quality.好吧,我可以根据绘制的画布数量导出多页的 pdf,但是从 canvas 绘制的图像质量非常低。 Finally, my doubt is, how can I export it with higher quality?最后,我的疑问是,我怎样才能以更高的质量导出它?

Theres a clever trick to i crease the resolution.我有一个聪明的技巧来提高分辨率。 step 1 make your canvas twice bigger like this: step 1使您的 canvas 大两倍,如下所示:

canvas.width=innerWidth*2;
canvas.height=innerHeight*2;

step 2 to make canvas cover entire width set its width and height from css like this: step 2使 canvas 覆盖整个宽度 从 css 设置其宽度和高度,如下所示:

canvas{ width:100%; }

thats it.而已。 At the end you will have doubled the image resolution and make sure you use width:100%;最后,您将图像分辨率翻倍,并确保使用width:100%; in css not as its attribute in html.在 css 中不作为其在 html 中的属性。

Hope that works for you.希望这对你有用。

If you are using Konva you should use its method to do an export.如果您使用的是Konva ,您应该使用它的方法进行导出。

stage.toDataURL()

If you want to increase quality of output image you can use pixelRatio property.如果要提高 output 图像的质量,可以使用pixelRatio属性。

// it will produce 4x bigger image
stage.toDataURL({ pixelRatio: 2})

https://konvajs.org/docs/data_and_serialization/High-Quality-Export.html https://konvajs.org/docs/data_and_serialization/High-Quality-Export.html

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

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