<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>draw html to canvas</title> <style> * { margin: 0; padding: 0; } .tools { border-bottom: 1px solid #ccc; padding: 10px; } .html { width: 100%; height: 200px; } .buttons { text-align: right; } .container { flex: 1; } label { display: block; text-align: center; font-size: 20px; } .canvas { border-top: 1px solid #ccc; } #canvas { width: 100%; height: 100%; } </style> </head> <body> <div class="tools"> <textarea class="html"></textarea> <div class="buttons"> <button onclick="reset()">重置</button> <button onclick="render()">绘制html到canvas</button> </div> </div> <div class="container"> <div class="browser"> <label>浏览器渲染</label> <div id="browser"></div> </div> <div class="canvas"> <label>canvas渲染</label> <canvas id="canvas"></canvas> </div> </div> </body> <script src="../../dist/index.umd.js"></script> <script src="./html.js"></script> <script> const DrawHtml2Canvas = window.DrawHtml2Canvas.default; const textarea = document.querySelector('.html'); const browser = document.querySelector('#browser'); const canvas = document.querySelector('#canvas'); const ctx = canvas.getContext('2d'); textarea.value = html; window.addEventListener('resize', debounce(render, 300)); function reset() { textarea.value = html; render(); } function debounce(fn, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(function() { fn.apply(arguments); }, delay); }; } async function render() { browser.innerHTML = textarea.value; const {devicePixelRatio} = window; const render = DrawHtml2Canvas.fromHTML(textarea.value); render.rootNode.style.set('width', `${window.document.body.clientWidth}px`); // 加载html中使用的图片 await render.loadSource(); // 计算布局 render.layout(ctx); // 获取网页尺寸 const {offsetWidth, offsetHeight} = render.rootNode; // 高清适配 ctx.save(); canvas.height = offsetHeight * devicePixelRatio; canvas.width = offsetWidth * devicePixelRatio; ctx.scale(devicePixelRatio, devicePixelRatio); // 绘制图像到canvas上 render.draw(ctx); ctx.restore(); } render(); </script> </html>