利用 html2canvas 做个简单的诗词卡片生成器

时间:2023-03-09 17:12:02
利用 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')
// 显示图片
})

最终效果:

利用 html2canvas 做个简单的诗词卡片生成器

项目 demo源码