图片裁剪的预览和上传

两个主要的问题解决:

如何实现本地预览?

只需要上传图片生成base64的格式,然后挂载到dom上就可以了。

如何实现图像部分的上传?

使用canvas进行画出裁剪完的图片即可。

具体代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片裁剪</title>
</head>
<body>

<input type="file"/>

<img class="preview" alt="" src=""/>
<button>生成截图后的file对象</button>


<script>
  const ipt = document.querySelector('input[type=file]');
  const preview = document.querySelector('.preview');
  const button = document.querySelector('button');

  ipt.onchange = function(e) {
    const file = e.target.files[0];
    console.log(file)
    const reader = new FileReader();
    reader.onload =(e)=>{
      console.log(e.target.result);
      preview.src = e.target.result;


    };
    reader.readAsDataURL(file);
  }

  button.onclick = function() {
      //进行裁剪: 裁剪我们需要在原图的裁剪坐标,原图中裁剪的宽高,裁剪后的缩放尺寸也就是宽高
      //我们如果想要定位裁剪的位置,需要知道四个参数,原图的宽高,以及裁剪的x和y坐标。
      const cutInfo = {
          //要裁剪的坐标
          x:300,
          y:200,
          //原图尺寸
          cutWidth:300,
          cutHeight:300,
          //裁剪完缩放的尺寸
          width:100,
          height:100,
      }
      //生成canvas
      const canvas = document.createElement('canvas');
      canvas.width = cutInfo.width;
      canvas.height = cutInfo.height;
      const ctx = canvas.getContext('2d');
      // 下面的两个0,0 是把图片画到canvas中的位置,就是靠左靠上。
      ctx.drawImage(preview, cutInfo.x, cutInfo.y,cutInfo.width,cutInfo.height,  0, 0,cutInfo.width,cutInfo.height);

      //canvas方法,转成二进制
      canvas.toBlob((blob)=>{
          //blob转换成  File
          const file = new File([blob], 'avatar.jpeg', {type: 'image/jpeg'});
          console.log(file);
          //使用ajax 上传到服务器即可
      },'image/jpeg');
      document.body.appendChild(canvas);
  }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值