例如有一段有趣的对话,需要通过聊天记录形式展现出来分享,想到通过网页设计是可以实现的,那么如何生成出来呢,在这里给具体讲一讲吧。
网页布局
创建一个网页文件index.html,代码如下
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>chat-room</title>
    <script src="./comon/dom-to-image.min.js"></script>
    <style>
        <!-- 样式 -->
    </style>
</head>
<body>
    <div id="app" class="chat-room">
        <div class="expand" id="box">
            <div class="chat-room-header">
                <div>{{navigatoBarTitleText}}</div>
            </div>
            <div class="chat-room-body">
                
            </div>
        </div>
        <div class="chat-room-footer">
            <button @click="onclick">生成图像</button>
        </div>
    </div>
	<!-- template 1 -->
	<!-- template 2 -->
    <script>
        window.onload = function(){
            //...加载,初始化逻辑
        }
    </script>
</body>
</html>
使用时要引入一个插件dom-to-image.min.js,这是一个能将页面显示效果生成一个图片的功能
模板布局
之前有写了注释如template 1和template 2,那里写实现两个不同的模板布局,
气泡模板
再写两个模板布局,用于显示两个不同的聊天气泡布局,
这是表示自己的,代码如下
<script id="template1" type="html/plain">
     <div class="msg">
         <div class="my">
             <div class="m">
                 {{item.msg}}
             </div>
             <div>
                 <img class="head" src="{{item.head}}" />
             </div>
         </div>
     </div>
 </script>
这是表示对方的,代码如下
 <script id="template2" type="html/plain">
     <div class="msg">
         <div class="other">
             <div>
                 <img class="head" src="{{item.head}}" />
             </div>
             <div class="m">
                 {{item.msg}}
             </div>
         </div>
     </div>
 </script>
注意了,看着页面代码好像
Vue写法,若是使用vue框架生成好像有问题,就写纯html网页纯脚本处理就会没问题的
加载逻辑
分两步实现,一个提供数据,另一个渲染,
聊天数据
定义的数据是这样的,代码如下
const data = {
 	navigatoBarTitleText:'TA',
     list:[],
     myHead:'favicon.ico',
 };
 data.list = [
     { ismy:true, msg:'hello tom', head:data.myHead },
     { ismy:false, msg:'hello', name:'tom', head:data.myHead },
     //省略更多...
 ];
// ...
渲染模板
实现渲染模板的方法是这样的,代码如下
function renderHTML(node,key,value){
     let obj = {};
     if(typeof key == 'string') {
         obj[key] = value;
     }else{
         for(let k in key) {
             obj['item.'+k] = key[k];
         }
     }
     let html;
     if(typeof node == 'string'){
         html = node;
     }else{
         html = node.innerHTML;
     }
     for(let k in obj){
         let reg = new RegExp(`{{${k}}}`,'g');
         html = html.replace(reg,obj[k]);
     }
     if(node.innerHTML) node.innerHTML = html;
     return html;
 }
然后,写加载初始化逻辑,代码如下
 let node = document.getElementById('box');
 const tLabel = 'timer';
 console.time(tLabel);
 
 renderHTML(node,'navigatoBarTitleText',data.navigatoBarTitleText);
 let template1 = document.getElementById('template1');
 let template2 = document.getElementById('template2');
 console.timeEnd(tLabel);
 let body = node.querySelector('.chat-room-body');
 let template = '';
 data.list.forEach(item=>{
     if(item.ismy) template += renderHTML(template1,item);
     else template += renderHTML(template2,item);
 })
 body.innerHTML = template;
 let button = document.querySelector('button');
 button.addEventListener('click',()=>{
     domtoimage.toPng(node).then((dataUrl)=>{
         clickDownloadLink(dataUrl)
     }).catch(function(err){
         console.error('oops, something went wrong!', err);
         
     })
 });
这里看到
domtoimage.toPng(node)就是从一个网页节点生成图片的,
可以生成海报,但只能是纯HTML页面才有效哦
图片预览
这个就是在浏览器上实现下载图片和图片预览的方法,代码如下
 function clickDownloadLink(url){
     let elem = document.createElement('a');
     elem.setAttribute('href',url);
     elem.setAttribute('target','_blank');
     elem.style.display='none';
     document.body.appendChild(elem);
     elem.click();
     document.body.removeChild(elem);
 }
修改样式
最后,边浏览边修改,调整样式,达到聊天记录逼真效果
body{
	margin: 0;
}
.chat-room{
    display: flex;
    flex-direction: column;
    height: 100vh;
}
.chat-room .chat-room-header{
    padding: 10px;
    text-align: center;
    color: aliceblue;
    background-color: black;
}
.chat-room .expand,
.chat-room .chat-room-body{
    flex: 1;
}
.chat-room .chat-room-body{
    overflow-y: auto;
}
.chat-room .msg{
    flex: 1;
    margin: 10px;
}
.chat-room .msg .m{
    flex: 1;
    margin: 5px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 6px;
    box-sizing: border-box;
    line-height: 34px;
}
.chat-room .msg .head{
    width: 50px;
    height: 50px;
    margin: 0 2px;
}
.chat-room .msg .my,
.chat-room .msg .other{
    display: flex;
    flex-direction: row;
}
.chat-room .msg .my .m{
    margin-left: 50px;
    background-color: #fff;
    border-bottom-right-radius: 0;
}
.chat-room .msg .other .m{
    margin-right: 50px;
    background-color: rgb(16, 199, 138);
    border-bottom-left-radius: 0;
}
运行测试
在浏览器上运行,点击生成图像按钮,生成图片效果图如下
 
经过测试,获取长条图没问题;
⚠ 不要伪造聊天记录哦,真真假假还是容易分辨出来的




















