网页截图并添加文字、图片
安装依赖#
yarn add html2canvas
实现代码#
toImage() {
// 手动创建一个 canvas 标签
const canvas = document.createElement("canvas")
// 获取父标签,意思是这个标签内的 DOM 元素生成图片
// imageTofile是给截图范围内的父级元素自定义的ref名称
let canvasBox = this.$refs.imageTofile
// 获取父级的宽高
const width = parseInt(window.getComputedStyle(canvasBox).width)
const height = parseInt(window.getComputedStyle(canvasBox).height)
// 宽高 * 2 并放大 2 倍 是为了防止图片模糊
canvas.width = width * 2
canvas.height = height * 2
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const context = canvas.getContext("2d");
context.scale(2, 2);
const options = {
backgroundColor: null,
canvas: canvas,
useCORS: true
}
html2canvas(canvasBox, options).then((canvas) => {
var img = new Image();
// 需要添加文字的图片
img.src = "/img/borders.png";
img.setAttribute("crossOrigin", 'Anonymous')
img.onload = () => {
var ctx = canvas.getContext("2d");
// 将图片添加到canvas
ctx.drawImage(img, width - 200, 100, 170, 110)
// 设置字体
ctx.font = "22px 微软雅黑 bolder"
// 设置字体颜色
ctx.fillStyle = "#06ebe7"
// 添加文字和位置
ctx.fillText("经度 114.22", width - 180, 132);
ctx.fillText("维度 32.43", width - 180, 164);
ctx.fillText("电流 12.12", width - 180, 196);
let dataURL = canvas.toDataURL("image/png")
this.imageFile = dataURL;
this.dialogTableVisible = true;
}
})
}
仅作记录,如果有什么不对的地方欢迎大家指正
作者:TanXJ
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?