capture cropped image from video stream with javascript
Asked Answered
H

1

0

I am taking a picture from a video using this tutorial

HTML:

    <canvas id="canvas" style="display:none;" ></canvas>
    <div class="output">
      <img id="photo" alt="" src="">
    </div>

JS

let imgElement = document.querySelector("#photo");
function takePicture(results) {
      let canvas = document.getElementById('canvas');
      let context = canvas.getContext('2d');

      if (width && height) {
          canvas.width = width;
          canvas.height = height;
          context.drawImage(results.image, 0, 0, canvas.width, canvas. Height);

          let data = canvas.toDataURL('image/png');
          imgElement.setAttribute('src', data);
      } else {
        clearPhoto();
      }
  }

It works and gives me an image of the full screen but I need a CROPPED image - just some part in the middle of the screen - the face of the user.

I try to:

context.drawImage(results.image, 0, 0, canvas. Width, canvas. Height, 100, 100, 300, 300);

but it only shrinks the image. I also tried to make a copy of this image in another canvas and image element but it comes up empty.

How to crop it properly?

Handicap answered 9/1, 2023 at 19:30 Comment(3)
I don't want to use extra libraries. Since I already know the coordinates of the rectangle in the centre of the screen drawImage() is a simples way. But I cant understand why it doesn't crop properly.Handicap
this is what I want to do. but in my case, it won't crop the image just shrink itHandicap
@Yogi in the best answer example from your link: how to replace an image with what in Canvas? If I want in the image to be cropped 'O' instead of 'Google'?Handicap
H
0

I managed to crop the image by using second image element: Added to HTML:

<canvas id="canvas" style="display:none;" ></canvas>
<div class="output">
  <img id="photo" alt="" src="">
  <img id="cropped-photo" alt="" src="">
</div>

In JS I added a new function that crop image:

     function cropImage(x, y, w, h)  {
       var fullImage = document.getElementById('photo'),
       image = document.getElementById('cropped-photo'),
       canvas = document.getElementById('canvas'),
       ctx = canvas.getContext('2d');

       ctx.clearRect(0, 0, canvas.width,canvas.height);
       ctx.drawImage(fullImage,x, y, w, h,0,0,canvas.width,canvas.height);
       let data = canvas.toDataURL('image/png');
       image.setAttribute('src', data);
  };
Handicap answered 16/1, 2023 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.