0

For creating a thumbnail from a video, i use this code:

<video controls>
    <source src="data/uploads/mainvideo-1601674168.mp4" type="video/mp4">                       
</video>
<canvas width="90" height="50"></canvas>                    
<button onclick="snap()">Take screenshot</button>

And the js:


<script>
// Get handles on the video and canvas elements
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
// Get a handle on the 2d context of the canvas element
var context = canvas.getContext('2d');
// Define some vars required later

var w, h, ratio;
// Define the size of the rectangle that will be filled (basically the entire element)
context.fillRect(0, 0, w, h);
// Grab the image from the video
context.drawImage(video, 0, 0, w, h);


// Add a listener to wait for the 'loadedmetadata' state so the video's dimensions can be read
video.addEventListener('loadedmetadata', function() {
    // Calculate the ratio of the video's width to height
    ratio = video.videoWidth / video.videoHeight;
    // Define the required width as 100 pixels smaller than the actual video's width
    w = 90;
    // Calculate the height based on the video's width and the ratio
    h = parseInt(w / ratio, 10);
    // Set the canvas width and height to the values just calculated
    canvas.width = w;
    canvas.height = h;          
}, false);

// Takes a snapshot of the video
function snap() {
    // Define the size of the rectangle that will be filled (basically the entire element)
    context.fillRect(0, 0, w, h);
    // Grab the image from the video
    context.drawImage(video, 0, 0, w, h);
}
</script>

Now when i click on the button, the thumbnail appears. I am not so familiar with js but how can i let appear the thumbnail immediately without clicking on the button?

I tried this at the end of the js but that doesn't work (jquery is loaded)

$(document).ready(function() {
    snap();
});
3
  • call snap() from video.addEventListener('loadedmetadata', function() ? Commented Oct 3, 2020 at 21:10
  • The thumbnail appears, but he is black Commented Oct 3, 2020 at 21:16
  • detect when video is loaded: stackoverflow.com/a/8685070/2275490 and place the snap() function there Commented Oct 3, 2020 at 21:34

1 Answer 1

1

You can just call snap() on the last line of your script. You are using JS, so when you are using onclick="snap()" you are calling the function snap() with javascript with the html onclick event.

Sign up to request clarification or add additional context in comments.

1 Comment

Check the question title: How to load a function without click event in javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.