Printing HTML5 Canvas in the correct size

前端 未结 3 1726
迷失自我
迷失自我 2021-02-06 13:30

Is there a correct way to specify the size of a canvas element in for example millimeters so that if I print it out it will have the correct size?

I\'ve tried this simpl

3条回答
  •  粉色の甜心
    2021-02-06 14:20

    Part 1: How many canvas pixels are required to generate a 50mm printed drawing?

    Printers typically print at 300 pixels per inch.

    In millimeters: 300ppi / 25.4 mm-in = 11.81 pixels per millimeter.

    So if you want to print a 50mm drawing you would calculate the required pixel size like this:

    50mm x 11.81ppm = 590.5 pixels (591 pixels)

    And you resize the canvas to have 591 pixels (assuming square) like this:

    // resize the canvas to have enough pixels to print 50mm drawing
    c.width=591;
    c.height=591;
    

    Part 2: Exporting the canvas as an image

    To print the canvas, you will need to convert the canvas into an image which you can do with context.toDataURL.

    // create an image from the canvas
    var img50mm=new Image();
    img50mm.src=canvas.toDataURL();
    

    Part 3: Convert the exported image to proper print resolution

    context.toDataURL always creates an image that is 72 pixels per inch.

    Printers typically print at higher resolution, maybe 300 pixels per inch.

    So for the exported image to print properly on the page, the exported image must be converted from 72ppi to 300ppi.

    The ImageMagick library can do the conversion: http://www.imagemagick.org/

    It's a server side tool so you will have to bounce the exported image off your server (probably using AJAX to round-trip your image).

    ImageMagick works in PHP, IIS and other server environments.

    Here's an example which use PHP to convert the image resolution and echo the converted image back to the caller:

    // Assume you've uploaded the exported image to
    // "uploadedImage.png" on the server
    setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
      $im->setImageResolution(300,300);
      $im->readImage("uploadedImage.png");
      $im->setImageFormat("png");
      header("Content-Type: image/png");
      echo $im;
    ?>
    

    Final Part: Print it!

    The converted file you receive back from the server will print a 50mm square image on your 300ppi printer.

提交回复
热议问题