Search code examples
pngfabricjs

Is it possible to set the PNG physical pixel dimensions using FabricJS?


The PNG specification includes physical pixel dimensions (see here). Does Fabric.js support setting these values? If so, how can these be set?

Edit: I should mention that I am trying to do this entirely in the browser. I'm not using NodeJS.


Solution

  • fabricJS does not support DPI values on output, but lucky enough i wrote a small library that will let you do that!

    It works on blob and dataurl: https://www.npmjs.com/package/changedpi

    I know seems pure advertising but i think this piece of code will do that and it does just that, it works for both PNG and JPEG.

    // create the dataUrl at standard 72dpi
    var dataUrl = canvas.toDataURL('image/jpeg', 0.92);
    var daurl150dpi = changeDpiDataUrl(dataUrl, 150);
    

    or

    
    // create the blob at standard 72dpi
    canvas.toBlob(function(blob) {
      changeDpiBlob(blob, 300).then(function(blob){
        // use your changed blob
      })
    },'image/jpeg', 0.92);
    

    The method it uses here are not the one from fabricJS, for the dataUrl there is no problem since you can generate a dataurl and pass it to this function here, while for the blob you have to use

    fabricCanvas.toCanvasElement(...) then move from canvasElement to blob if for any reason you prefer the blob advantages over dataUrls.