如何将 HTML 网页转换为图像?
在我的一个项目中,我需要实现一个将 HTML 网页转换为图像的功能。我首先想到的是使用内置库,例如dom-to-image,或者使用Chrome Headless或Puppeteer之类的包装库。在工作过程中,我偶然发现了这种使用纯 JavaScript 的技术。
让我们尝试不使用任何库来实现这一点。
使用 Canvas 将 HTML 网页转换为图像。
出于安全考虑,我们不能直接将 HTML 绘制到 Canvas 中。我们将采用另一种更安全的方法。
步骤
- 创建包含渲染内容的 SVG 图像。
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
</svg>
- 在 SVG 中插入一个
<foreignObject>
包含 HTML 的元素。
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
<foreignObject width="100%" height="100%">
</foreignObject>
</svg>
- 在节点内添加 XHTML 内容
<foreignObject>
。
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">.
<style>em{color:red;}</style>
Hey there...
</div>
</foreignObject>
</svg>
- 创建图像对象并将图像的 src 设置为图像的数据 url。
const tempImg = document.createElement('img')
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">Hey there...</div></foreignObject></svg>')
- 将此图像绘制到 Canvas 上,并将画布数据设置为目标
img.src
。
const newImg = document.createElement('img')
newImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml">Hey there...</div></foreignObject></svg>')
// add event listener to image.
newImg.addEventListener('load', onNewImageLoad)
// method to draw image to canvas and set data to target img.src
function onNewImageLoad(e){
ctx.drawImage(e.target, 0, 0)
targetImg.src = canvas.toDataURL()
}
您可以在 CodeSandox 中找到完整的代码!
使用 SVG 和 Canvas 安全的原因?
SVG 图像的实现非常严格,因为我们不允许 SVG 图像加载外部资源,即使是同一域名下的资源也是如此。SVG 图像中不允许使用脚本,其他脚本也无法访问 SVG 图像的 DOM,而且 SVG 图像中的 DOM 元素也无法接收输入事件。因此,无法将特权信息(例如 中的完整路径<input type="file">
)加载到表单控件中并进行渲染。
从安全角度来看,脚本不能直接接触渲染到画布上的 DOM 节点这一限制非常重要。
我尝试简要介绍一下这个主题和步骤。欢迎补充相关内容。😅
快乐学习!👩💻
文章来源:https://dev.to/jasmin/how-to-turn-html-webpage-into-an-image-n1c