html2canvas实现截取指定区域或iframe的区域

官网文档: http://html2canvas.hertzen.com/

使用的是 jquery 3.2.1   html2canvas 1.0.0-rc.7

截取根据id的指定区域:

var canvasOtherTopHeight = $(‘.heading‘).height() + 31 + $(‘#site-navbar‘).height();  // .heading是指定区域父级上面同级的dom,因为存在高度,所以要计算到内
function createCanvas(id, obj) {
    // 1.获取高度
    let canvasObj = $(# + id);
    // 2.区域为画布
    // console.log(‘--==‘, canvasObj.width(), canvasObj.height(), canvasObj.offset().left, canvasObj.parent().parent().position().top);

    html2canvas(canvasObj.get(0), {
        useCORS: true,
        width: canvasObj.width() + 5,
        height: canvasObj.height() - excelHeight,
        x: canvasObj.offset().left,
        y: canvasObj.parent().top + canvasOtherTopHeight
    }).then(canvas => {
        // canvasObj.parent().find(‘.target-canvas-img‘).attr(‘src‘, canvas.toDataURL(‘image/png‘, 1.0));
        canvasObj.parent().find(.canvas-wrapper .canvas-word).append(canvas);
    });

}

截取根据id的iframe的区域:

function createCanvas(id, obj) {
    // 1.获取高度
    let canvasObj = $(# + id);
    // 2.答案区域为图片
    // console.log(‘--==‘, canvasObj.width(), canvasObj.height(), canvasObj.offset().left, canvasObj.parent().parent().position().top);
    // excel的高度
    let excelHeight = canvasObj.find(.answer-con-excel-container iframe).height();

    let iframeHtml = canvasObj.find(.answer-con-excel-container iframe); // 获取iframe内容
    let iframeBody = iframeHtml.contents().find(body)[0];
    html2canvas(iframeBody, {
        allowTaint: true,
        useCORS: true,
        width: 820, // TODO 截屏按照1920*1080分辨率下的预览窗口宽高
        height: 800,
        x: 0,
        y: 0
    }).then(canvas => {
        // canvasObj.parent().find(‘.target-canvas-img-excel‘).attr(‘src‘, canvas.toDataURL(‘image/png‘, 1.0));
        canvasObj.parent().find(.canvas-wrapper .canvas-excel).append(canvas);
    })
}

 其中参数 width height 可根据效果进行增减

html2canvas实现截取指定区域或iframe的区域

上一篇:Kubernetes之network: failed to set bridge addr: "cni0" already has an IP address different from xxx问题


下一篇:.net 过滤器