加入收藏 | 设为首页 | 会员中心 | 我要投稿 驾考网 (https://www.jiakaowang.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

javascript-html2canvas-怎么定义顶部,左侧,底部,右侧以进行自动裁剪?

发布时间:2023-03-14 12:56:54 所属栏目:教程 来源:
导读:我有一个1280×768页面.下面的代码正在制作1280×768的全页快照,但是我需要忽略顶部10px,底部10px,底部10px,右侧10px.

您可以在document.body.appendChild(canvas)之前或之后进行裁剪/缩放吗? ?使用C
我有一个1280×768页面.下面的代码正在制作1280×768的全页快照,但是我需要忽略顶部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
    });
};
您可以简单地使用屏幕外画布,在其上绘制具有所需偏移量的渲染画布.

这是一个快速编写的功能,可能无法满足所有要求,但至少可以给您一个提示:
 请注意,它使用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.


 

(编辑:驾考网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章