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

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

这是一个快速的书面功能,可能无法满足所有要求,但至少可以给您一个想法: 请注意,它使用最新的HTML2Canvas版本(0.5.0-BETA4),该版本现在返回承诺。

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®在其帧上使用了一些强大的安全性,因此我们无法在此处进行实时演示,但是您可以在此 JSFIDDLEDLEDLEDLEDLEDLEDLEDDLEDLEDLED

中找到一个。

哦,对于那些想要支持旧html2canvas版本的ES5版本的人,您只需要将裁剪功能包装在昂贵的回调中,或者这里是懒惰者的小提琴。

最新更新