In my app, I wrote a code which allows a user to take a picture using their camera which is connected to the computer.
Implementation:
I have used a webcam, which show a video element and the source is the camera:
function onSuccess (stream) {
this.video.srcObject = stream;
}
navigator.getUserMedia({video: true}, onSuccess, onFailure)
When the user clicks on a button I create a snapshot from the video:
function takeSnapshot (width, height, savePicture) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(this.video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(function (blob) {
savePicture(blob);
}, "image/jpeg");
}
Now, I need to zoom into the camera and crop the video around the center, since I want to remove the background around the photo. I don't want to implement this using CSS since I want to save the picture cropped and zoomed too. I want this zooming in the video view and also when taking the snapshot with zoom.
The camera has no zooming option of its own.
Is there an option to zoom and crop in the video stream?
context.drawImage()
has optional parameters to "scale" image (sWidth, sHeight).
To move the image and "crop", you may set additional params (dx, dy).
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
But this a direct way of zoom&crop by JS. If you need ready UI for such functionality, you may combine your code with something like this: http://deepliquid.com/projects/Jcrop/demos.php?demo=thumbnail (I didn't try it, just have it in bookmarks)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With