js div 转canvas 场景出图

代码

参考博客 JS实现将div生成高清图片并保存本地 https://blog.csdn.net/qq_42583562/article/details/87755493

//div出图 需引入 html2canvas.js  下载地址 http://html2canvas.hertzen.com/
function exportDivAsPNG(divname,pngname){
    //创建一个新的canvas
    var tempCanvas = document.createElement("canvas");
    let tempDiv = document.querySelector((‘#‘+divname));
    var w = parseInt(window.getComputedStyle(tempDiv).width);
    var h = parseInt(window.getComputedStyle(tempDiv).height);
    //将canvas画布放大若干倍,然后盛放在较小的容器内,就显得不模糊了
    tempCanvas.width = w * 2;
    tempCanvas.height = h * 2;
    tempCanvas.style.width = w + "px";
    tempCanvas.style.height = h + "px";
    //可以按照自己的需求,对context的参数修改,translate指的是偏移量
    //  var context = canvas.getContext("2d");
    //  context.translate(0,0);
    var context = tempCanvas.getContext("2d");
    context.scale(0, 0);
    html2canvas(document.querySelector((‘#‘+divname)), { canvas: tempCanvas }).then(function(canvas) {
    var MIME_TYPE = "image/png";
    var imgURL = canvas.toDataURL(MIME_TYPE);
    var dlLink = document.createElement(‘a‘);
    dlLink.download = pngname;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(‘:‘);
    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
    });
    };
    
//得到当前时间字符串,格式为:YYYY-MM-DD HH:MM:SS    
function curentTimeString() {   
    var now = new Date();    
    var year = now.getFullYear();       //年  
    var month = now.getMonth() + 1;     //月  
    var day = now.getDate();            //日      
    var hh = now.getHours();            //时  
    var mm = now.getMinutes();          //分  
    var ss=now.getSeconds();            //秒    
    var clock = year + "-";    
    if(month < 10) clock += "0";         
    clock += month + "-";    
    if(day < 10) clock += "0";   
    clock += day + " ";  
    if(hh < 10) clock += "0";  
    clock += hh + ":";  
    if (mm < 10) clock += ‘0‘;   
    clock += mm+ ":";      
    if (ss < 10) clock += ‘0‘;   
    clock += ss;  
    return(clock);   
    }; 
    //使用方式
    exportDivAsPNG(‘mapDiv‘,curentTimeString());

效果

js  div 转canvas 场景出图

js div 转canvas 场景出图

上一篇:.Net Core下DllImport使用方法及扩展


下一篇:express路由、静态托管、ejs模板引擎