javascript - 如何在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()。
推荐阅读
- bootstrap-4 - 切换按钮问题
- xaml - 将自定义按钮插入 BottomBar 外壳
- arrays - C中数组的大小小于预期
- dependency-injection - 是否可以使用 Unity 作为与 Restier 结合使用的 DI 框架
- javascript - 是什么导致 Square 集成出现此错误
- javascript - 无法访问for循环中的数据
- sql-server - SQL Server 中没有 PIVOT 的行到列
- pybind11 - 转换 std::complex
进入 pybind11::object - amazon-web-services - 子文件夹上的 AWS S3 AccessDenied
- javascript - 如何禁用多个输入的提交按钮(jQuery Homework)