zoukankan      html  css  js  c++  java
  • 利用 html2canvas 做个简单的诗词卡片生成器

    html2canvas 简介

    html2canvas 顾名思义,就是一个可以把 DOM 元素转换成图片的类库,常用于网页截图。网页截图常见的应用场景是,在意见反馈里对当前页面进行截图,方便反馈页面出现的问题,比如页面样式出错,举报网站上的违规行为等等。

    除了截图外,还可以用来制作一些在线生成图片的功能,比如这个在线生成条形图

    做一个诗词卡片生成工具

    所谓诗词卡片生成工具,就是能把某一首诗词,生成一张精美的诗词卡片。当然对于不懂设计的我来说,想要做到精美有点困难。

    实现原理是,利用富文本编辑器,让用户输入诗词,生成 HTML,再通过 html2canvas 把 HTML 生成图片。

    大致实现

    安装依赖。wangeditor 是一个比较不错的富文本编辑器,至少界面不会太丑。

    npm install html2canvas --save-dev
    npm install wangeditor--save-dev
    

    把 wangeditor 封装成 Vue 组件。

    <template>
        <div>
            <div class="rich-editor" id="editorElem" style="text-align:left"></div>
        </div>
    </template>
    
    <script>
        import E from 'wangeditor'
    
        export default {
            data() {
                return {
                    editorContent: ''
                }
            },
            props: {
                value: {
                    type: String,
                    default: ''
                }
            },
            mounted() {
                this.editorContent = this.value
    
                this.editor = new E('#editorElem')
                this.editor.customConfig.onchange = html => {
                    this.editorContent = html
                    this.$emit('input', this.editorContent)
                }
                this.editor.create()
                this.editor.txt.html(this.editorContent)
            },
            destroyed() {
    //            this.editor.destroy()
            }
        }
    </script>
    
    

    调用富文本编辑器。

    <my-rich-editor v-model="content"></my-rich-editor>
    

    把用户输入的富文本,保存在一个 div 里面。captureStyle 是用户设置的卡片的样式。

    <div id="capture" v-html="content" :style="captureStyle"></div>
    

    最后利用 html2canvas 生成卡片,供用户下载。

    html2canvas(document.querySelector('#capture')).then(canvas => {
        let img = canvas.toDataURL('image/png')
       // 显示图片
    })                           
    

    最终效果:

    项目 demo源码

  • 相关阅读:
    1052 卖个萌 (20 分)
    1046 划拳 (15 分)
    1051 复数乘法 (15 分)
    1042 字符统计 (20 分)哈希
    1041 考试座位号 (15 分)哈希
    1061 判断题 (15 分)
    1093 字符串A+B (20 分)简单哈希
    Hibernate框架
    SVN的安装与介绍
    easyUI的简单操作
  • 原文地址:https://www.cnblogs.com/yunser/p/use-html2canvas-and-wangeditor-make-a-tool.html
Copyright © 2011-2022 走看看