首页 > Web开发 > 详细

js div 转canvas 场景出图

时间:2021-09-06 03:54:06      阅读:26      评论:0      收藏:0      [点我收藏+]

代码

参考博客 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 场景出图

原文:https://www.cnblogs.com/hustshu/p/15226684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!