利用 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源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM