效果图
实现el-image图片预览时,下方跟随一个背景颜色的白色字体
实现思路:使用画布,先引入该图片,再画一个带有透明度的矩形,最后再绘制文字。然后画布将这些内容放置到一张图上,转成对应的URL即可
<template>
<div class="demo-image__preview">
<el-image
style="width: 100px; height: 100px"
:src="url"
fit="contain"
@click="showImgViewer(item.url,item.name)"
/>
<el-image-viewer
v-if="imgViewerVisible"
@close="closeImgViewer"
:url-list="[currentImgViewerUrl]"
/>
</div>
</template>
<script lang="ts" setup>
import { onMounted, ref, } from 'vue'
const url =
'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg'
const imgViewerVisible = ref<boolean>(false)
const currentImgViewerUrl = ref<String>('')
const showImgViewer = (pictureUrl: String, pictureName: String) => {
imgViewerVisible.value = true
currentImgViewName.value = pictureName
let canvas = document.createElement('canvas')
const context:any = canvas.getContext('2d')
let img:any = new Image()
img.crossOrigin = ''
img.src = pictureUrl
//加载图片
img.onload = () => {
canvas.setAttribute('width',img.width)
canvas.setAttribute('height',img.height + 52)
//绘制图片
context.drawImage(img,0,0,img.width, img.height)
//绘制底部矩形
context.fillStyle = 'rgba(29,33,41,0.6)'; //fillstyle设置填充颜色
context.fillRect(0,img.height,img.width,52);
//字体
context.font = '22px Arial'
context.fillStyle='#fff'; //fil1Style设置填充颜色
context.textAlign = "center"
context.textBaseline = "middle"
//字体文字,显示位置 图片上需要n个文字就写n个context.fillText(文字,上下,左右);
context.fillText(pictureName, img.width / 2,img.height + 26)
let type = pictureUrl.replace(/.+\./g,'')
//合成图片
currentImgViewerUrl.value = canvas.toDataURL(`image/$(type}`,1.0)
}
}
const closeImgViewer = () =>{
imgViewerVisible.value = false
currentImgViewerUrl.value = ''
}
</script>
<style scoped>
.demo-image__error .image-slot {
font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
font-size: 30px;
}
.demo-image__error .el-image {
width: 100%;
height: 200px;
}
</style>
文章评论