[英]How to load a function without click event in javascript
为了从视频创建缩略图,我使用以下代码:
<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>
和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>
现在,当我单击按钮时,会出现缩略图。 我对 js 不太熟悉,但是如何在不单击按钮的情况下立即显示缩略图?
我在 js 的末尾试过这个,但不起作用(jquery 已加载)
$(document).ready(function() {
snap();
});
您可以在脚本的最后一行调用snap()
。 您正在使用 JS,因此当您使用onclick="snap()"
时,您正在使用带有 html onclick 事件的 javascript 调用函数 snap()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.