当前位置 : 主页 > 网页制作 > html >

使用html2canvas 生成img

来源:互联网 收集:自由互联 发布时间:2021-06-12
//canvas- imgfunction convert2canvas() { var el = document.getElementById("dayimg");//要截图的div var saveImg = document.getElementById("saveImg"); var canvas = document.createElement("canvas"); var scale = window.devicePixelRatio;//获取
//canvas-> img
function convert2canvas() {
    var el = document.getElementById("dayimg");//要截图的div
    var saveImg = document.getElementById("saveImg");
    var canvas = document.createElement("canvas");
    var scale = window.devicePixelRatio;//获取设备的显示参数
    var ctx = canvas.getContext("2d")
    var rect = el.getBoundingClientRect(); //获取元素相对于视察的偏移量
    var w = el.offsetWidth;
    var h = w/0.69;

    console.log(w)
    canvas.width = w * scale;
    canvas.height = h * scale;
    canvas.style.width = w;
    canvas.style.height = h;
    ctx.scale(scale, scale);
    ctx.translate(-rect.left, -rect.top); //设置context位置,值为相对于视窗的偏移量负值,让图片复位
    html2canvas(el, {
        scale : scale,
        canvas : canvas,
        width : w,
        height : h,
        logging : false,
        useCORS : true
    }).then(function(canvas) {
        var dataUrl = canvas.toDataURL("jpeg");
        saveImg.src = dataUrl;
    });
    $(".dayimg").hide()
}
网友评论