Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

问题描述

想要实现一个头像截图上传功能,在canvas上渲染一张图片,图片可放大缩小,再在canvas指定一个区域(红色框),
有如下待解决问题:
1.不管图片放大缩小,都只截取该区域,如图中红色区域
2.去掉canvas上截图多出来的图片(左上角绿色前头)
3.得出来的图片,只要红色框截取的部分,完整的图不要,其实就是绿色前头

1604297074(1).png

相关代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      position: relative;
    }

    .box-border {
      position: absolute;
      width: 100px;
      height: 100px;
      left: 100px;
      top: 100px;
      border: 2px solid red;
    }
  </style>
</head>

<body>
  <div class='box'>
    <canvas id="canvas" style="display:block;border:1px solid #aaa;">
      您的浏览器尚不支持canvas
    </canvas>
    <input type="range" id="scale-range" min="0.5" max="2.0" step="0.01" value="1.0"
      style="display:block;margin:20px;" />
    <div class='box-border'></div>
  </div>
  <div>
    <p>img</p>
    <img id='img' src="" alt="">
  </div>
  <script>
    var canvas = document.getElementById("canvas")
    var context = canvas.getContext("2d")
    var slider = document.getElementById("scale-range")
    var image = new Image()
    window.onload = function () {

      canvas.width = 300
      canvas.height = 500

      var scale = slider.value
      image.src = "img.jpg"
      image.onload = function () {
        drawImageByScale(scale)

        slider.onmousemove = function () {
          scale = slider.value
          drawImageByScale(scale)
        }
      }
    }
    
    //放大缩小
    function drawImageByScale(scale) {

      var imageWidth = 300 * scale
      var imageHeight = 500 * scale

      x = canvas.width / 2 - imageWidth / 2
      y = canvas.height / 2 - imageHeight / 2

      context.clearRect(0, 0, canvas.width, canvas.height)  //第滑动一次input,range,清空canvas
      context.drawImage(image, x, y, imageWidth, imageHeight)
      getImg(canvas, context)
    }
    
    //获取截图
    function getImg(canvas, context) {
      context.drawImage(image, 0, 0, 100, 100);
      var url = canvas.toDataURL("image/png")
      document.getElementById('img').setAttribute('src', url)
    }
  </script>
</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

有很多这样的组件

vue-image-crop https://github.com/jczzq/vue-...
react-easy-crop https://ricardo-ch.github.io/...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...