如何打印canvas元素? [英] How to print a canvas element?
问题描述
我的页面上有一个canvas元素。我在它上面绘制一个图像和用户输入的一些数据。在按下按钮我想把画布发送到打印机,打印在纸上。我尝试使用此插件: jQuery.printElement ,像这样:
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 paper. I tried to use this plug-in: jQuery.printElement, like that:
按钮代码:
<a href="javascript:print_voucher()">PRINT</a>
'print_voucher()'函数:
'print_voucher()' function:
function print_voucher()
{
$("#canvas_voucher").printElement();
}
canvas_voucher是我的画布元素的ID。它打印了页面,但没有打印画布。我试图像这样使用它:
canvas_voucher is the ID of my canvas element. It printed the page, but didn't print the canvas. I tried to use it like that as well:
$("#canvas_voucher img").printElement();
但是这还没有启动打印机。
But that didn't even start the printer.
那么我该怎么办呢?如何打印画布的内容?
So how can I do that? How can I print the content of the canvas?
** EDIT **
这里是代码创建我的画布,并尝试用它创建一个图像:
**EDIT** Here's the code that creates my canvas and tries to create an image with it:
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.');
}
}
推荐答案
找到问题并修复它。
显然这是一行的安全问题:
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';
之后,我创建了一个函数来从canvas创建一个图像,并在'img中调用它。 onload'部分:
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);
}
现在工作了!
这篇关于如何打印canvas元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!