Canvas实现新旧图片对比

2023-12-21 12:03:53

在这里插入图片描述

<!DOCTYPE html>
<html>

<head>
  <title>Canvas</title>
  <meta charset="UTF-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="edge">
  <meta name="keywords" />
  <meta name="description" />
  <meta name="viewport"
    content="width=device-width, initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="msapplication-tap-highlight" content="no" />
  <style>
    #canvas {
      display: none;
    }

    #mergedImage {
      max-width: 100%;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  新旧图片对比:
  <img id="mergedImage">

  <script>
    var image1 = new Image();
    var image2 = new Image();

    image1.onload = function () {
      image2.onload = function () {
        var canvas = document.getElementById("canvas");
        var context = canvas.getContext("2d");
        var widthRatio = Math.min(image1.width / image2.width, image2.width / image1.width);

        var scaledWidth1 = image1.width * widthRatio;
        var scaledHeight1 = image1.height * widthRatio;

        var scaledWidth2 = image2.width * widthRatio;
        var scaledHeight2 = image2.height * widthRatio;

        var croppedWidth = Math.min(scaledWidth1, scaledWidth2);

        canvas.width = croppedWidth;
        canvas.height = scaledHeight1 + scaledHeight2;

        context.drawImage(image1, 0, 0, croppedWidth, scaledHeight1);
        context.drawImage(image2, 0, scaledHeight1, croppedWidth, scaledHeight2);

        var mergedImage = document.getElementById("mergedImage");
        mergedImage.src = canvas.toDataURL();
        mergedImage.style.display = "block"; // 显示合并后的图像
      };

      image2.src = "../images/indexCont3_img1.jpg"; // 图像2的URL
    };

    image1.src = "../images/indexCont3_img2.jpg"; // 图像1的URL
  </script>
</body>

</html>

文章来源:https://blog.csdn.net/qq_44681558/article/details/135123582
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。