// 将 base64 数据转为 Blob 对象
const dataURLtoBlob = (dataurl) => {
const arr = dataurl.split(',') // 将 base64 数据按逗号分割为数组
let bstr = window.atob(arr[1]) // 对数据部分进行 base64 解码
let n = bstr.length // 获取解码后的字符串长度
let u8arr = new Uint8Array(n) // 创建等长的 Uint8Array
while (n--) {
u8arr[n] = bstr.charCodeAt(n) // 将每个字符的 Unicode 编码存入数组
}
return new Blob([u8arr], { type: 'png' }) // 返回 Blob 对象,指定类型为 'png'
}
// 提交处理
const handleSubmit = async () => {
// 动态添加样式,解决文字偏移问题
const style = document.createElement('style') // 创建一个 <style> 元素
document.head.appendChild(style) // 将 <style> 添加到 <head>
style.sheet?.insertRule('body > div:last-child img { display: inline-block; }') // 添加 CSS 规则
// 使用 html2canvas 将页面元素转为 Canvas
html2canvas(customModel.value, {
scale: 1, // 设置缩放比例
scrollX: 0, // 禁用水平滚动
scrollY: 0 // 禁用垂直滚动
}).then((canvas) => {
style.remove() // 动态样式使用后删除
let dataURL = canvas.toDataURL('image/png') // 将 Canvas 转换为 base64 数据
const blobUrl = dataURLtoBlob(dataURL) // 将 base64 数据转为 Blob
const fileUrl = URL.createObjectURL(blobUrl) // 创建 Blob 的 URL
// 创建 a 标签用于下载图片
const addElement = document.createElement('a') // 创建一个 <a> 元素
addElement.href = fileUrl // 设置 href 为生成的文件 URL
addElement.download = '下载.png' // 设置下载文件名
document.body.appendChild(addElement) // 将 <a> 添加到页面
addElement.click() // 模拟点击以触发下载
document.body.removeChild(addElement) // 下载完成后移除 <a>
})
}
html2canvas截图后文字向下偏移解决
于 2024-07-25 16:45:28 首次发布