Some browsers will unfortunately clear the canvas before printing.
One way to get around this is to insert an image element in the DOM with the canvas and then define two CSS classes:
Then the key is to update the image with the content of the canvas each time needed.
function updatePrint() { var img = document.getElementById('printImage'), /// get image element canvas = document.getElementById('canvas'); /// get canvas element img.src = canvas.toDataURL(); /// update image }Then define a couple of CSS rules based on media types:
@media screen { #canvas {display:block} /* or inline-block */ #printImage {display:none} } @media print { #canvas {display:none} #printImage {display:block} }(defining one for screen is strictly not necessary as long as the print definition comes after the standard rule for canvas and image).
Note on print and resolution: when you print a canvas remember that the resolution matters - the screen is typically the equivalent to 72/96 DPI while the print is typically 300 DPI. This may cause the print to look blurry unless you increase the size of the canvas and use CSS to keep it within its screen size. For tips on this see for example this answer: . You would also need to handle scaled mouse positions (not covered here).
Note that CORS restrictions apply here in case the canvas has been tainted by different origin images (images drawn to it coming from another domain than the page itself).
有些浏览器会不幸的是印刷前清除画布。
解决此问题的方法是将与帆布DOM图像元素,然后定义两个CSS类:
然后,关键是要在每一次的油画的内容更新的图像需要。
function updatePrint() { var img = document.getElementById('printImage'), /// get image element canvas = document.getElementById('canvas'); /// get canvas element img.src = canvas.toDataURL(); /// update image}然后定义一对基于媒体类型的CSS规则:
@media screen { #canvas {display:block} /* or inline-block */ #printImage {display:none} }@media print { #canvas {display:none} #printImage {display:block} }(定义一个屏幕不必要的只要打印定义是帆布和图像标准的规则后)。
在打印分辨率注意:当您打印帆布记住分辨率的问题-屏幕通常是相当于72 / 96 dpi的打印时,通常是300天。这可能导致打印看起来模糊的除非你增加画布使用CSS来保持它在屏幕尺寸大小。提示在这看到例如这样的回答:。你还需要处理规模的鼠标位置(这里不包括)。
注:CORS限制在案件的帆布被不同来源的图像(图像被吸引到它来自另一个域比页面本身)。