How to print a canvas element?

后端 未结 2 1058
囚心锁ツ
囚心锁ツ 2021-01-19 05:12

I have a canvas element on my page. I draw an image over it and some data that the user entered. On a press of a button I want to send the canvas to printer, to print it on

相关标签:
2条回答
  • 2021-01-19 05:39

    This will convert the canvas to a .png image URL and open it in a new browser window

    The Print Dialog is triggered to let the user print the page.

    function print_voucher(){
        var win=window.open();
        win.document.write("<br><img src='"+canvas.toDataURL()+"'/>");
        win.print();
        win.location.reload();
    }
    

    Here is example code:

    <style>
        body{ background-color: ivory; }
        canvas{border:1px solid red;}
    </style>
    
    <script>
    $(function(){
    
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
    
        ctx.fillStyle="gold";
        ctx.strokeStyle="blue";
        ctx.lineWidth=5;
        ctx.rect(50,50,100,100);
        ctx.fill();
        ctx.stroke();
    
        function print_voucher(){
            var win=window.open();
            win.document.write("<br><img src='"+canvas.toDataURL()+"'/>");
            win.print();
            win.location.reload();
        }
    
        $("#printVoucher").click(function(){ print_voucher(); });
    
    
    }); // end $(function(){});
    </script>
    
    </head>
    
    <body>
        <canvas id="canvas" width=300 height=300></canvas><br>
        <button id="printVoucher">Print</button>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-19 05:45

    Found the problem and fixed it. Apparently it was a security issue at this line:

    img.src = 'https://someurl.com/image.jpg';
    

    Once it was pointing out to a server, it was considered as a potential security threat. So I changed it to:

    img.src = 'images/image.jpg';
    

    After that I created a function to make an image from the canvas and called it within the 'img.onload' part:

    ...
    img.onload = function(){
        ctx.drawImage(img,0,0);
        ctx.fillStyle="#CCC";
        ctx.font="bold 20px Arial";
        ctx.fillText(visitor_name, 750, 270);
        ctx.fillText(visitor_identity_num, 750, 295);
        ctx.font="bold 25px Arial";
        ctx.fillText(unique_number, 620, 325);
        draw_voucher_img();
    ...
    
    function draw_voucher_img()
    {
       var canvas = $("#canvas_voucher")[0];
       var voucher = canvas.toDataURL();
       $("#voucher_img").attr("src", voucher);
    }
    

    Now it worked!

    0 讨论(0)
提交回复
热议问题