How to print canvas content using javascript

前端 未结 2 817
滥情空心
滥情空心 2021-01-23 05:30

I am using canvas for writing purpose using jsp page. I am able to write any message on canvas, (canvas message i have created..)

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 06:09

    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.

提交回复
热议问题