接上文 对比 html 文档差异

将富文本转换成 html 后,尝试对比修改前后的页面,最开始的方案是对比 html 的 dom 内的文字和样式。
问题在于 html 的样式很灵活,不同的 css 组合起来可能显示效果是一样的。
后面想到新的方法,就是将两段 html 分别渲染成页面,截图对比像素差异,这个有一个类似的实现库 Resemble.js 实现效果代码如下。

image

这个方法的问题在于不如 git 那种文本对比灵活匹配。
目前想不到更好的方法了,求指教。

复制
<!-- 两段 html 渲染对比 -->
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>HTML 渲染图像对比</title>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/resemble.js"></script>
  <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
  <style>
    #preview1, #preview2 {
      width: 400px;
      height: auto;
      border: 1px solid #ccc;
      margin-bottom: 10px;
    }
    textarea {
      width: 400px;
      height: 150px;
    }
  </style>
</head>
<body>
  <h2>输入两段 HTML 代码进行渲染对比</h2>
  <div>
    <h3>HTML 1</h3>
    <textarea id="html1"><h2 style="background:#eee;padding:6px 10px;margin:0">旧 HTML</h2>
      <div id="oldPane" class="content">
        <h3>旧标题</h3>
        <p>这是一段<strong>原始</strong>文字。</p>
        <ul>
          <li>项 A</li>
          <li>项 B</li>
        </ul>
        <p>测试</p>
      </div></textarea>
    <div id="preview1"></div>
  </div>
  <div>
    <h3>HTML 2</h3>
    <textarea id="html2"><h2 style="background:#eee;padding:6px 10px;margin:0">新 HTML</h2>
      <div id="newPane" class="content">
        <h3>新标题</h3>
        <p>这是一段<strong>修改后</strong>文字。</p>
        <ul>
          <li>项 A</li>
          <li>项 B 已改</li>
          <li>项 C 新增</li>
        </ul>
      </div></textarea>
    <div id="preview2"></div>
  </div>
  <button onclick="renderAndCompare()">渲染并对比</button>
  <h3>差异图:</h3>
  <div id="result"></div>
  <script>
    async function renderAndCompare() {
      const html1 = document.getElementById('html1').value;
      const html2 = document.getElementById('html2').value;

      const preview1 = document.getElementById('preview1');
      const preview2 = document.getElementById('preview2');

      preview1.innerHTML = html1;
      preview2.innerHTML = html2;

      const canvas1 = await html2canvas(preview1);
      const canvas2 = await html2canvas(preview2);

      const img1 = canvas1.toDataURL();
      const img2 = canvas2.toDataURL();

      resemble(img1)
        .compareTo(img2)
        .onComplete(function(data) {
          const diffImage = new Image();
          diffImage.src = data.getImageDataUrl();
          document.getElementById('result').innerHTML = `
            <p>差异百分比:${data.misMatchPercentage}%</p>
          `;
          document.getElementById('result').appendChild(diffImage);
        });
    }
  </script>
</body>
</html>

image

标签: none

添加新评论