300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 使用Canvas合成多张图片和文字为一张图片

使用Canvas合成多张图片和文字为一张图片

时间:2021-11-24 10:08:08

相关推荐

使用Canvas合成多张图片和文字为一张图片

完整demo代码,vue

<!-- 图片合成demo --><template><div class="view-wrap"><h3>我是canvas图片文字合成组件</h3><img ref="img1" src="./1.jpg" alt /><img ref="img2" src="./2.jpg" alt /><div><el-input v-model="text" placeholder="请输入内容" style="width: 250px;"></el-input><el-button type="primary" @click="handleConposeImg">合成</el-button></div><div ref="photo" class="photo"></div><canvas v-show="false" ref="myCanvas" id="myCanvas"></canvas></div></template><script>export default {components: {},data() {return {text: ''}},computed: {},methods: {onCreateCanvas() {let img1 = this.$refs.img1let img2 = this.$refs.img2// console.log(img1.naturalWidth, img1.naturalHeight) 可获取图片的原始宽度和高度let img1Height = img1.naturalHeightlet img2Height = img2.naturalHeightlet canvasWidth = 200 // 这里设置固定值let canvasHeight = img1.naturalHeight + img2.naturalHeight // 合成的画布高度为两张图片高度之和let canvas = this.$refs.myCanvaslet context = canvas.getContext('2d')canvas.width = canvasWidth // canvas画布宽度canvas.height = canvasHeight // canvas画布高度// 将img1、img2等依次加入画布context.drawImage(img1, 0, 0, 200, img1Height) // 加入图片1context.drawImage(img2, 0, img1Height, 200, img2Height) // 加入图片2context.fillStyle = 'red' // 设置文字的填充颜色context.font = 'italic 20px Georgia' // 设置文字的填充样式context.fillText(this.text, 10, 140) // 在画布中添加文字let newImg = new Image()newImg.src = canvas.toDataURL('image/png') // canvas画布导出图片this.$refs.photo.append(newImg) // 将图片插入div中展示出来},// 点击合成按钮,执行合成方法handleConposeImg() {this.onCreateCanvas()}},mounted() {// // HACK:加上延时避免 mounted 方法比页面加载早执行// this.$nextTick(() => {// setTimeout(() => {//this.onCreateCanvas()// }, 100)// })}}</script><style lang="scss" scoped></style>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。