I want to crop a video in HTML 5.
<video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video>
The resolution of the video is 640x360, but when I set the width
attribute to 200, the video will rescale (retain the aspect ratio). How to crop the video (cut off, say, 220 pixels from both the left and right side) through HTML or Javascript? Is it even possible without cropping the video through video editing software?
We must define an extra CSS rule to shift the video to the left, in order to make sure that the video is cropped on both sides. We can do it like this: div. container video { margin-left: -220px; } . However, this answer led me to the solution.
You can use the object-fit property in conjunction with object-position to adjust the area of the image to crop. The object-position property requires two values: x% and y% to position the image (the default position is 50% 50%).
The crop tool can help! Cropping is the process of moving or adjusting the edges of an image or video clip. Often used for photo editing, it is also helpful when editing video. With cropping, you can remove unnecessary or distracting portions of a video clip or change its dimensions to fit within a certain area.
I would recommend you to do it with CSS and a wrapper:
HTML
<div class="container"> <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> </div>
CSS
.container{ width: 200px; overflow:hidden; display:block; height: 360px; } #glass{ margin-left: -220px; }
I ran into the same need (wanting to crop video on the fly instead of cropping the actual video).
My solution is pretty simple, and works so that you don't need to specify the height or width of the container in absolutes, therefore it's responsive. I've just used inline styles here for simplicity, but you can easily move the css to classes etc.
<div style="overflow: hidden;"> <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" style="margin-top: -10.5%; margin-bottom: -10.5%"></video> </div>
In this example I used negative margins in percentages. Keep in mind that using percentages, that they're calculated based on the container's width. So it's not 10.5% of the videos's height. I think you'd need to use javascript if you were wanting to do that. However, with this approach you can also use vh
or vw
units. Or do what Alvaro suggested and set widths on the container if you want it to be absolutely sized, and use px
to set the margins.
Check out this codepen for more examples!
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