Search code examples
javascripthtmlcsshtml2canvas

html2canvas - how to define top, left, bottom, right to have auto crop?


I have a page 1280x768. following code is making 1280x768 full page snapshot, but i need to ignore from top 10px, from left 10px from bottom 10px, from right 10px.

Can you do that crop/scale or so before or after document.body.appendChild(canvas); ? using CSS3 or JS or so?

window.takeScreenShot = function() {
    html2canvas(document.getElementById("top"), {
        onrendered: function (canvas) {
            document.body.appendChild(canvas);
        },
        width:1280,
        height:768
    });
};

Solution

  • You can simply use an offscreen canvas, on which you will draw your rendered canvas with the desired offset.

    Here is a quickly written function which may not fulfill all requirements, but which can at least give you an idea : note that it uses latest html2canvas version (0.5.0-beta4), which now returns a Promise.

    function screenshot(element, options = {}) {
      // our cropping context
      let cropper = document.createElement('canvas').getContext('2d');
      // save the passed width and height
      let finalWidth = options.width || window.innerWidth;
      let finalHeight = options.height || window.innerHeight;
      // update the options value so we can pass it to h2c
      if (options.x) {
        options.width = finalWidth + options.x;
      }
      if (options.y) {
        options.height = finalHeight + options.y;
      }
      // chain h2c Promise
      return html2canvas(element, options).then(c => {
        // do our cropping
        cropper.canvas.width = finalWidth;
        cropper.canvas.height = finalHeight;
        cropper.drawImage(c, -(+options.x || 0), -(+options.y || 0));
        // return our canvas
        return cropper.canvas;
      });
    }    
    

    And call it like that

    screenshot(yourElement, {
      x: 20, // this are our custom x y properties
      y: 20, 
      width: 150, // final width and height
      height: 150,
      useCORS: true // you can still pass default html2canvas options
    }).then(canvas => {
      //do whatever with the canvas
    })
    

    Since stacksnippets® uses some strong security on their frames, we can't make a live demo in here, but you can find one in this jsfiddle.

    Oh and for those who want an ES5 version supporting the old html2canvas version, you just have to wrap the cropping function in the onrendered callback, or here is a fiddle for the lazy ones.