添加的文字是写入图片的,文字会随着图片的大小、位置改变而改变
完成的效果:
代码:
<template>
<div>
<div>写入前</div>
<img src="https://img0.baidu.com/it/u=1384155777,1106731832&fm=253&fmt=auto&app=138&f=JPEG?w=600&h=400" />
<div>写入后</div>
<img :src="currentImg">
</div>
</template>
<script>
export default {
data() {
return {
currentImg: ""
}
},
mounted() {
this.addTextEvent()
},
methods: {
addTextEvent() {
var _this = this
let canvas = document.createElement("canvas");
canvas.width = 600;
canvas.height = 400;
let myImage = new Image();
myImage.src = "https://img0.baidu.com/it/u=1384155777,1106731832&fm=253&fmt=auto&app=138&f=JPEG?w=600&h=400"; // 需要添加文字的图片
myImage.crossOrigin = "Anonymous";
let context = canvas.getContext("2d");
myImage.onload = function () {
context.drawImage(myImage, 0, 0, canvas.width, canvas.height);
context.font = "20px Courier New";
context.fillStyle = 'red'
// context.textAlign = 'end' //文字右对齐
context.fillText("我是写入的文字", 250, 350); // 文字的内容和位置
let base64 = canvas.toDataURL("image/png"); // "image/png" 这里注意一下
_this.currentImg = base64
}
}
},
}
</script>
本文含有隐藏内容,请 开通VIP 后查看