html2canvas - 如何定义自动裁剪的顶部,左侧,底部,右侧?

时间:2016-12-16 23:50:07

标签: javascript html5 css3 html2canvas

我有一个页面1280x768。下面的代码正在制作1280x768整页快照,但我需要忽略前10px,从左10px到底10px,从右10px。

你可以在document.body.appendChild(canvas);之前或之后做那种裁剪/缩放吗?使用CSS3或JS左右?

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

1 个答案:

答案 0 :(得分:4)

您可以简单地使用屏幕外的画布,在该画布上绘制具有所需偏移的渲染画布。

这是一个快速编写的功能,可能无法满足所有要求,但至少可以给你一个想法:  请注意,它使用latest html2canvas version (0.5.0-beta4),现在返回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;
  });
}    

并称之为

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
})

由于stacksnippets®在其框架上使用了一些强大的安全性,我们无法在此处制作实时演示,但您可以在 jsfiddle 中找到一个。

哦,对于那些想要支持旧的html2canvas版本的ES5版本的人来说,你只需要在onrendered回调中包装裁剪功能,或者对于懒惰的回调来说这里是a fiddle

相关问题