Print canvas contents

后端 未结 4 1976
粉色の甜心
粉色の甜心 2020-12-11 09:41
var print = document.createElement(\'button\');
var canvas = document.createElement(\'canvas\');
var ctx = canvas.getContext(\'2d\');

canvas.width = 300;
canvas.hei         


        
4条回答
  •  感动是毒
    2020-12-11 10:09

    You need to make the actual canvas at print size then scale it on screen using CSS rules.

    The browser will always use the internal bitmap size first and adjust that to the print or screen. If the bitmap is then of high resolution you will get better result on the print.

    But mind you though, you will need to scale every coordinate and size when you print to the canvas. You will also need to prioritize screen versus print as one of them will look worse (if you prioritize print it will not look super on screen and vica verse).

    Here is a modified example of your canvas which is now equivalent of 300 DPI (versus default 96 DPI). You can see it looks about the same on screen but will be much sharper when you print it.

    /// conversion factor for scale, we want 300 DPI in this example
    var dpiFactor = 300 / 96,
        width = 400,
        height = 100;
    
    /// set canvas size representing 300 DPI
    canvas.width = width * dpiFactor;
    canvas.height = height * dpiFactor;
    
    /// scale all content to fit the 96 DPI display (DPI doesn't really matter here)
    canvas.style.width = width + 'px';
    canvas.style.height = height + 'px';
    
    /// scale all sizes incl. font size
    ctx.font = (15 * dpiFactor).toFixed(0) + 'px sans-serif';
    
    /// scale all positions
    ctx.fillText('Fill Text, 18px, sans-serif', 10 * dpiFactor, 20 * dpiFactor);
    

    Simply use wrapper functions to do all the math for you:

    function fillText(txt, x, y) {
        ctx.fillText(txt, x * dpiFactor, y * dpiFactor);
    }
    

提交回复
热议问题