HTML5 canvas, convert canvas to PDF with jspdf.js

前端 未结 5 731
陌清茗
陌清茗 2021-02-04 12:10

I am trying to convert HTML5 canvas to PDF in JavaScript but I get a black background PDF. I tried to change the background color but still get black. The following is code I am

5条回答
  •  甜味超标
    2021-02-04 13:07

    I had the same problem, e.g. the first time when i create a pdf the canvas image is ok, but all the other next, came out black. No picture!

    The workaround i found is as follows: after each call to pdf.addImage() i redraw the picture in the canvas. It works now fine for me.

    EDIT: As requested, here some more details:

    Let say i have a canvas drawing function like this (just an example, it doesn't matter):

    function drawCanvas(cv) {
      for(var i=0; i

    I had to fix my printing function as follows:

    var cv=document.getElementById('canvas');
    printPDF(cv) {
        var imgData=cv.toDataURL("image/jpeg", 1.0);
        var doc=new jsPDF("p","mm","a4");
        doc.addImage(imgData,'JPEG',15,40,180,180);
        drawCanvas(cv); // <--- this line is needed, draw again
    }
    drawCanvas(cv); // <--- draw my image to the canvas, ok
    printPDF(cv); // first time is fine
    printPDF(cv); // second time without repaint would be black
    

    I admit, i did'nt investigate further, just happy that this works.

提交回复
热议问题