JSFiddle - React, Tailwind, and code Playground
by Sam88
HTML
<div style="position: absolute">
<canvas id="canvasOne" width="500" height="300" style="border: 1px black solid">
Your browser does not support HTML5 Canvas.
</canvas>
<br>
<button type="button" onclick="javascript:play();">Play</button>
<button type="button" onclick="javascript:pause();">Pause</button>
<button type="button" onclick="javascript:replay();">Reset</button>
</div>
JavaScript
//video canvas
window.addEventListener('load', eventWindowLoaded, false);
var videoElement;
var videoDiv;
var videoWidth;
var videoHeight;
var canvasWidth;
var canvasHeight;
var timer;
var wRatio;
var hRatio;
var ratio;
var valH;
var valW;
var topOffset;
var leftOffset;
function eventWindowLoaded() {
var theCanvas = document.getElementById("canvasOne");
canvasWidth = theCanvas.width;
canvasHeight = theCanvas.height;
videoElement = document.createElement("video");
videoElement.addEventListener("loadedmetadata", function () {
videoWidth = this.videoWidth;
videoHeight = this.videoHeight;
//alert(videoWidth+" "+videoHeight);
});
videoDiv = document.createElement('div');
document.body.appendChild(videoDiv);
videoDiv.appendChild(videoElement);
videoDiv.setAttribute("style", "display:none;");
videoElement.setAttribute("src", "http://www.himom.it/trussardi/video/video.mp4");
videoElement.addEventListener("canplaythrough",videoLoaded,false);
}
function play() {
videoElement.play();
}
function pause() {
videoElement.pause();
}
function replay() {
videoElement.load();
}
function videoLoaded(event) {
canvasApp();
}
function canvasApp() {
wRatio = videoWidth/canvasWidth;
hRatio = videoHeight/canvasHeight;
ratio = wRatio>hRatio?wRatio:hRatio;
valH = videoHeight/ratio;
valW = videoWidth/ratio;
topOffset = (canvasHeight - valH)/2;
leftOffset = (canvasWidth - valW)/2;
clearInterval(timer);
function drawScreen () {
context.drawImage(videoElement , 0, 0, videoWidth, videoHeight,
leftOffset,topOffset,valW, valH);
//(img,sx,sy,swidth,sheight,x,y,width,height);
}
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
timer=setInterval(drawScreen, 33);
}