canvas图片裁剪demo

<!DOCTYPE html>
<html>
<head>
  <title>Image Cropping</title>
</head>
<body>
  <input type="file" id="fileInput" accept="image/*">
  <canvas id="canvas"></canvas>
  <script>
    // 获取input框
    const fileInput = document.getElementById('fileInput');
    // 初始化canvas
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    // 监听input框里面的变化
    fileInput.addEventListener('change', (event) => {
      // 获取文件
      const file = event.target.files[0];
      // 读取文件[对象]
      const reader = new FileReader();
      // 读取完成后执行回调
      reader.onload = function (event) {
        // 创建一个Image[对象]
        const img = new Image();
        // 监听加载完成后执行回调函数
        img.onload = function () {
          const x = 100; // 切割区域的起始横坐标
          const y = 100; // 切割区域的起始纵坐标
          const width = 200; // 切割区域的宽度
          const height = 200; // 切割区域的高度
          // 设置Canvas的宽度和高度为图片的宽度和高度
          canvas.width = img.width;
          canvas.height = img.height;
          // 通过drawImage方法,在Canvas上绘制完整的图片
          ctx.drawImage(img, 0, 0);
          // 通过getImageData方法执行切割操作,返回一个裁剪的ImageData对象
          const croppedImageData = ctx.getImageData(x, y, width, height);
          canvas.width = width;
          canvas.height = height;
          // 通过putImageData方法,将切割后的ImageData渲染到Canvas上
          ctx.putImageData(croppedImageData, 0, 0);
        };
        img.src = event.target.result;
        // console.log('-base64:-->>>',img.src);
      };
      reader.readAsDataURL(file);
    });
  </script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值