Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - How to print canvas content using javascript

I am using canvas for writing purpose using jsp page. I am able to write any message on canvas, (canvas message i have created..) enter image description here but after this when i want to print this canvas message using javascript print code i am not able to print canvas content. below you can see print preview for that.. enter image description here

I want to print canvas message that i have created on canvas. Please help me out from this problem, any help will be appreciate..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It can happen that your canvas is cleared when dialogs show - this happens typically in the Chrome browser.

Without having source code to try with as you didn't post any I'll make a theoretic answer that you can try out - I would suggest two possible solutions:

  1. Add an event handler for resize. When triggered redraw the content (which means you need to store the points etc. that you draw or make an off-screen canvas to store a copy). I have experienced that this event triggers (in Chrome) when a dialog has cleared the canvas - if it works for print preview I am not sure - if not try next point:

  2. When you click your print button, extract the canvas as an image and replace (temporary) the canvas element with an image element setting the source to the data-uri from canvas. On the image's onload handler trigger the print code:

Example for second point:

/// create a reference to canvas element
var canvas = document.getElementById('myCanvas');

printBtn.addEventListener('click' function() {

    /// remove it from DOM (use parent element if any, for demo I use body)
    document.body.removeChild(canvas);

    var img = new Image;

    img.id = 'tempPrintImage';    /// give an id so we can remove it in next step
    img.onload = print;           /// onload handler triggers your print method
    img.src = canvas.toDataURL(); /// set canvas image as source

    document.body.appendChild(img);

}, false);

function print() {

    ...your print code here. On return reverse the elements: ...

    var img = document.getElementById('tempPrintImage');
    document.body.removeChild(img);
    document.body.appendChild(canvas);
}

The code may seem a bit over-loaded but the key point here is to preserve the content of the canvas. You can place the image on top instead and so forth.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...