最近迭代的时候因为新增了一个需求,需要前端提供素材及样式给后端,后端同步渲染,但是因为部分样式问题后端无法实现所以决定前端将页面生成图片然后传递给后端使用,本文记录一下使用的过程及遇到的部分问题。
现在将页面元素转换成图片的插件有很多,普遍使用的技术原理都是利用canvas或者SVG将页面元素转换成画布或者svg元素,然后再转成图片。这里我在考虑到速度、易用性、稳定性后选择使用html-to-imag,文档地址在这里,本文使用html-to-image版本1.11.11。
html-to-image的使用非常方便,内置了很多方法供我们使用:
import { toPng, toJpeg, toBlob, toPixelData, toSvg } from 'html-to-image';
这里根据具体需求选择不同的使用方式就好了,最开始我是用的toPng
方法,使用的时候遇到了一些问题,不过已经是五个月前的事儿了所以这里就跳过,我使用的是toBlob方法,个人也推荐使用toBlob方法。
import { toBlob } from 'html-to-image'
toBlob(node,config)
.then((blob)=> {
...
});
基础的使用如上所示,其中第二个参数是生成图片的一些配置,用于一些定制化的需求。
canvasWidth
和 canvasHeight
style
pixelRatio
window.devicePixelRatio
。cacheBust
true
。quality
1.0
(最高质量)。imagePlaceholder
undefined
。skipFonts
false
。fontEmbedCSS
undefined
。filter
undefined
。backgroundColor
undefined
。width
和 height
type
image/png
上面是部分配置项,更多的配置项和使用方法可以移步文档。
基础的使用方法说完了,下面说说使用过程中遇到的问题
在使用过程中我发现部分生成的图片没有元素,起初我以为是元素中图片的问题,后来发现部分元素的偏移使用的是定位部分使用的是transform,定位的top、left等值是可以正常捕捉到元素的,但是当使用transform的时候,因为偏移是相对自身的,所以会导致元素可能超出了生成的图片范围,这里我使用的方法是转图片的时候手动清除transform,转换完毕后再设置回去。
const transformList = []
const nodeTransform = node.style.transform
const rotateRegex = /rotate\([-.\d]+deg\)/
const match = nodeTransform.match(rotateRegex)
const isRotate = match && match[0] !== 'rotate(0deg)'
if (nodeTransform) {
node.style.transform = '' // 这里应该保留rotate,因为我这里不需要处理所以直接清除,rotate只作匹配展示
}
toBlob(node).then((res) => {
...
}).finally(() => {
requestAnimationFrame(() => {
node.style.transform = transformList[index] // 我这里使用了nodeList遍历所以用到了index,具体使用看个人实际情况
})
})
我们的页面中有部分元素是采用背景图然后设置background的方式实现的
background: url(...) 0% 0% / 100% 100% no-repeat;
当时排查到是背景图元素会导致生成图片变形后我尝试了使用其他背景参数去设置,无论是设置background-size
还是background-position
的其他值生成的图片都是被拉伸的。所以这里我采用第二种方案,转图片前将背景图转成图片元素然后再恢复。
// 在调用toBolb方法前添加下面代码
let backgroundImage = node.style.backgroundImage
let isBgRenderEle =
backgroundImage !== '' && backgroundImage !== 'url("")'
if (isBgRenderEle) {
const imgUrl = backgroundImage
.replace(/^url\(["']?/, '')
.replace(/["']?\)$/, '')
const imgNode = document.createElement('img')
imgNode.src = imgUrl
imgNode.style.width = '100%'
imgNode.style.height = '100%'
node.style.backgroundImage = ''
node.appendChild(imgNode)
}
// 转成图片后添加下面代码
if (isBgRenderEle) {
node.innerHTML = ''
node.style.backgroundImage = backgroundImage
backgroundImage = ''
isBgRenderEle = false
}