Canvas实现新旧图片对比

在这里插入图片描述

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值