This code works fine on mac Add onload:main() to the body tag Can run automatically after startup In the ios browser can not run automatically, after setting a button, click to point to main(). Click to play normally under ios onload cannot be executed
Both mac and ios use safari browser. How to make ios autoplay normal
function main() {
const video1= initializeVideo("mv/m4.mp4");
VIDEO_CANVAS = document.getElementById('video');
video1.addEventListener('loadeddata', (event) => {
const context = VIDEO_CANVAS.getContext("2d");
context.canvas.width = video1.videoWidth * (740 / video1.videoHeight);
context.canvas.height = 740;
processVideos(video1,0);
});
}
function processVideos(video1,frame1){
if(frame1 <=200 )
{ showVideoFrame(video1,frame1); frame1++; }
if(frame1>=200) {
location.reload();
}
setTimeout(function(){
processVideos(video1,frame1);
},30);
}
function showVideoFrame(video,frame){
var time = frame / 30 ;
video.currentTime=time;
const context=VIDEO_CANVAS.getContext("2d");
context.drawImage(video, 0, 0, VIDEO_CANVAS.width,VIDEO_CANVAS.height);
}
function initializeVideo(filename) {
var video = document.createElement('video');
video.src=filename;
video.load();
return video;
}
body content
<body onload="main()">
<center>
<canvas id="video"></canvas>
</center>
</body>
Is the idea to slow motion the video? It is not easy to jump from frame to frame, because you don't know how much of the video has been loaded. In this example I use the property defaultPlaybackRate on the video to control the speed. And then simply play the video and draw the current frame to the canvas every 30 ms. The interval is cleared when the video has ended.
If this is going to autoplay you can try to mute the video before playing it. An alternative could be to let the user interact with the page first, either clicking something (click event) or scrolling (scroll event) a bit. You can read more about it here: Autoplay guide for media and Web Audio APIs - Web media technologies | MDN
var VIDEO_CANVAS, interval;
document.addEventListener('DOMContentLoaded', e => {
VIDEO_CANVAS = document.getElementById('video');
const video = document.createElement('video');
video.defaultPlaybackRate = .4;
video.muted = true; // important for autoplay
video.addEventListener('canplaythrough', e => {
VIDEO_CANVAS.width = e.target.videoWidth * (200 / e.target.videoHeight);
VIDEO_CANVAS.height = 200;
e.target.play();
interval = setInterval(function() {showVideoFrame(video);}, 30);
});
video.addEventListener('ended', e => {
clearInterval(interval);
});
video.src = "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4";
});
function showVideoFrame(video) {
const context = VIDEO_CANVAS.getContext("2d");
context.drawImage(video, 0, 0, VIDEO_CANVAS.width, VIDEO_CANVAS.height);
}
<canvas id="video"></canvas>