如何打印canvas元素?

Iga*_*gal 4 printing html5 canvas

我的页面上有一个canvas元素.我在上面绘制一个图像和用户输入的一些数据.只需按一下按钮,我就可以将画布发送到打印机,然后将其打印在纸上.我尝试使用这个插件:jQuery.printElement,就像这样:

按钮代码:

<a href="javascript:print_voucher()">PRINT</a>
Run Code Online (Sandbox Code Playgroud)

'print_voucher()'功能:

function print_voucher()
{
    $("#canvas_voucher").printElement();
}
Run Code Online (Sandbox Code Playgroud)

canvas_voucher是我的canvas元素的ID.它打印了页面,但没有打印画布.我试着像这样使用它:

$("#canvas_voucher img").printElement();
Run Code Online (Sandbox Code Playgroud)

但这甚至没有启动打印机.

那我该怎么办呢?如何打印画布的内容?

**编辑** 这是创建我的画布并尝试使用它创建图像的代码:

function create_voucher(visitor_name, visitor_identity_num, unique_number)
{
var canvas = $("#canvas_voucher")[0];
if (canvas.getContext)
{
    var ctx = canvas.getContext('2d');

    // Draw image
    var img = new Image();
    img.src = 'https://someurl.com/image.jpg';

    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);
    }
    var voucher = canvas.toDataURL("image/png");
    $("#voucher_img").attr("src", voucher);
} else {
    alert('You need Safari or Firefox 1.5+ to see this.');
}
Run Code Online (Sandbox Code Playgroud)

}

mar*_*rkE 10

这会将画布转换为.png图像URL并在新的浏览器窗口中打开它

触发打印对话框以允许用户打印页面.

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

这是示例代码:

<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>
Run Code Online (Sandbox Code Playgroud)