2

I'm using konva.js to draw elements on an HTML Canvas. When the user finishes its design in the canvas, the creation can be exported into a PDF file. In this context, my HTML structure is the following:

  • a div "canvas" to append all the canvas
  • a div "canvas0/canvas1" and so on to append each konva-canvas
  • an auto-generated 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...).

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. Finally, my doubt is, how can I export it with higher quality?

soalrib
  • 589
  • 3
  • 9
  • 31

2 Answers2

1

Theres a clever trick to i crease the resolution. step 1 make your canvas twice bigger like this:

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:

canvas{ width:100%; }

thats it . At the end you will have doubled the image resolution and make sure you use width:100%; in css not as its attribute in html.

Hope that works for you.

  • 1
    Hi @Prashanthth Kumar, thank you for your answer. I did a similar trick, it might not be the most optimal approach but does the job :) – soalrib May 22 '21 at 15:49
1

If you are using Konva you should use its method to do an export.

stage.toDataURL()

If you want to increase quality of output image you can use pixelRatio property.

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

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

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • Hi @lavrton, thanks for your answer. That would be useful if I export directly from the konva-canvas to the pdf. But I'm using document.getContext('2d') to add an image to then add to the final PDF, which is where the canvas contents lose quality. – soalrib May 22 '21 at 15:47