I am having video clip which is due to play in Timer when Timer gets tick after few minutes.
What I want is whenever the video starts playing it should automatically go into FullScreen mode and when it stops it, however comes back to position because as soon as Video stops I have Timer Ticked.
I know this requestFullScreen() method but I don't know how to call it when video starts playing?
Any Help will be appreciated!!
Regards and Thanks!
var video = document.createElement('video');
video.src = 'urlToVideo.ogg';
video.style.width = window.innerWidth;
video.style.height = window.innerHeight;
video.autoPlay = true;
document.getElementById('video2').appendChild(video);
Are you looking for something like this?
video = document.getElementById('video');
function onTick(){
video.play();
}
video.onPlay = function() {
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.msRequestFullscreen) {
video.msRequestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen();
}
};
video.onended = function(e) {
if(video.exitFullscreen) {
video.exitFullscreen();
} else if(video.mozCancelFullScreen) {
video.mozCancelFullScreen();
} else if(video.webkitExitFullscreen) {
video.webkitExitFullscreen();
}
};
Do something like this :
<script>
window.onload = function(){
var el = document.getElementById("OnTick");
el.addEventListener("click", function(){
el.style.display = 'none';
var videoContener = document.getElementById('video2');
var video = document.createElement('video');
videoContener.style.width = window.innerWidth;
videoContener.style.height = window.innerHeight;
video.src = 'http://techslides.com/demos/sample-videos/small.ogv';
video.style.width = "100%";
video.autoPlay = true;
video.controls = true;
videoContener.appendChild(video);
}, false);
}
</script>
<body style='margin:0px'>
<div id='video2' style='overflow: hidden;'></div>
<span id='OnTick' style='width:20px;height:20px;background-color:#323232;display:block'> </span>
</body>
autoplay doesn't work
Related
guys i have two cameras that is
-the web camera
-the laptop camera
i want to stream those camera in a website
i already have some reference
here is some code that is working on jsfiddle
here
<video id="video" width="640" height="480" autoplay></video>
<button id="snap" class="sexyButton">Snap Photo</button>
<canvas id="canvas" width="640" height="480"></canvas>
<script>
// Put event listeners into place
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
} else if(navigator.mozGetUserMedia) { // WebKit-prefixed
navigator.mozGetUserMedia(videoObj, function(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 640, 480);
});
}, false);
</script>
that example can only connects and select 1 camera
i want to select and view two of my camera, any suggestion or solution guys?
you can also give me the JS fiddle
You can create two different streams, one for each camera, and show them simultaneously in two <video> tags.
The list of available devices is available using navigator.mediaDevices.enumerateDevices(). After filtering the resulting list for only videoinputs, you have access to the deviceIds without needing permission from the user.
With getUserMedia you can then request a stream from the camera with id camera1Id using
navigator.mediaDevices.getUserMedia({
video: {
deviceId: { exact: camera1Id }
}
});
The resulting stream can be fed into a <video> (referenced here by vid) by calling vid.srcObject = stream.
I have done this for two streams from two webcams simultaneously.
You cannot access two cameras simultaneously. The API would indicate otherwise, but something underlying seems to prevent it from working as expected. You can verify this by opening https://simpl.info/getusermedia/sources/ or http://googlechrome.github.io/webrtc/samples/web/content/getusermedia-source/ in two completely seperate windows, despite being able to select two streams only one is active at once - if you pick the same one in both windows, then it shows in both places.
The only workaround I was able to do was to flip-flop between the two streams, then draw the video to a canvas. Doing this I was able to do captures at around 1 fps, unfortunately the camera resets between frames, on one of my cameras I had to put in a delay to allow the auto white balance to kick in to get a decent image.
function webcam() {
if (!navigator.getUserMedia) {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
}
if (!navigator.getUserMedia) {
return alert('getUserMedia not supported in this browser.');
}
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var audioSource;
var cw = Math.floor(canvas.clientWidth / 2);
var ch = Math.floor(canvas.clientHeight/2);
//canvas.width = cw;
//canvas.height = ch;
//off dom video player
var video = document.createElement("video");
video.autoplay="autoplay";
video.addEventListener('playing', function(){
//delay for settling...
setTimeout(draw,1000,this,context,(currentSource*canvas.clientWidth/2),cw,ch);
},false);
function captureVideo() {
console.log("Capturing " + currentSource,videosources[currentSource]);
var mediaOptions = {
audio: {
optional: [{sourceId: audioSource}]
},
video: {
optional: [
{sourceId: videosources[currentSource].id}
]
}};
navigator.getUserMedia(mediaOptions, success, errorCallback);
}
var currentSource=0;
var videosources = [];
var lastStream;
function errorCallback(error){
console.log("navigator.getUserMedia error: ", error);
}
function success(stream) {
console.log("the stream" + currentSource,stream);
video.src = window.URL.createObjectURL(stream);
video.play();
lastStream=stream;
}
function next(){
if(lastStream){
lastStream.stop();
}
video.src = "";
if(currentSource < videosources.length-1){
currentSource+=1;
}
else
{
currentSource=0;
}
captureVideo();
}
function draw(v,c,l,w,h) {
if(v.paused || v.ended) return false;
console.log("drawing",l)
c.drawImage(v,l,0,w,h);
setTimeout(next,500);
}
MediaStreamTrack.getSources(function (sourceInfos) {
for (var i = 0; i != sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind === 'audio') {
console.log(sourceInfo.id, sourceInfo.label || 'microphone');
audioSource=sourceInfo.id;
} else if (sourceInfo.kind === 'video') {
console.log(sourceInfo.id, sourceInfo.facing, sourceInfo.label || 'camera');
videosources.push(sourceInfo);
} else {
console.log('Some other kind of source: ', sourceInfo);
}
}
console.log("sources",videosources)
next();
});
}
I'm doing one project using html and java-script but i'm new to java-script but i know little bit about js functionality..my project is based on Webcam and Captured images from my webcam i have completed upto Webcam and i takes pictures from my webcam and Now im problem is i want to save my captured images using captured button Id i tried but i cant get exact result.if any one knows please help me..
Here is my coding:'cam-video.html'
<div class="container" id="videophoto">
<div class="row">
<div class="col-sm-6 col-md-6">
<div id="container">
<video id="videoel" width="400" height="300" preload="auto" loop playsinline autoplay>
</video>
<canvas id="overlay" width="400" height="300"></canvas>
</div>
<button id="capture" class="pic">Capture</button><br />
<!--<img src="examples/media/audrey.jpg" />-->
<div class="alert alert-success" id="success-alert">
<button type="button" class="close" data-dismiss="alert">x</button>
<img src="" id="photo" alt="photo">
Here is my javascript:'mine.js'
<script>
var vid = document.getElementById('videoel');
var vid_width = vid.width;
var vid_height = vid.height;
var overlay = document.getElementById('overlay');
var overlayCC = overlay.getContext('2d');
/*********** Setup of video/webcam and checking for webGL support *********/
function enablestart() {
var starttbutton = document.getElementById('starttbutton');
starttbutton.value = "start";
starttbutton.disabled = null;
}
var insertAltVideo = function(video) {
// insert alternate video if getUserMedia not available
if (supports_video()) {
if (supports_webm_video()) {
video.src = "./media/cap12_edit.webm";
} else if (supports_h264_baseline_video()) {
video.src = "./media/cap12_edit.mp4";
} else {
return false;
}
return true;
} else return false;
}
function adjustVideoProportions() {
// resize overlay and video if proportions of video are not 4:3
// keep same height, just change width
var proportion = vid.videoWidth/vid.videoHeight;
vid_width = Math.round(vid_height * proportion);
vid.width = vid_width;
overlay.width = vid_width;
}
function gumSuccess( stream ) {
// add camera stream if getUserMedia succeeded
if ("srcObject" in vid) {
vid.srcObject = stream;
} else {
vid.src = (window.URL && window.URL.createObjectURL(stream));
}
vid.onloadedmetadata = function() {
adjustVideoProportions();
vid.play();
}
vid.onresize = function() {
adjustVideoProportions();
if (trackingStarted) {
ctrack.stop();
ctrack.reset();
ctrack.start(vid);
}
}
}
function gumFail() {
// fall back to video if getUserMedia failed
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("There was some problem trying to fetch video from your webcam, using a fallback video instead.");
}
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.msURL || window.mozURL;
// set up video
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({video : true}).then(gumSuccess).catch(gumFail);
} else if (navigator.getUserMedia) {
navigator.getUserMedia({video : true}, gumSuccess, gumFail);
} else {
insertAltVideo(vid);
document.getElementById('gum').className = "hide";
document.getElementById('nogum').className = "nohide";
alert("Your browser does not seem to support getUserMedia, using a fallback video instead.");
}
vid.addEventListener('canplay', enablestart, false);
/*********** Code for face tracking *********/
var ctrack = new clm.tracker();
ctrack.init();
var trackingStarted = false;
function startVideo() {
// start video
vid.play();
// start tracking
ctrack.start(vid);
// var time=setTimeout("alert('Two Faces Not Allowed')",3500);
trackingStarted = true;
// start loop to draw face
drawLoop();
}
function drawLoop() {
requestAnimFrame(drawLoop);
overlayCC.clearRect(0, 0, vid_width, vid_height);
//psrElement.innerHTML = "score :" + ctrack.getScore().toFixed(4);
if (ctrack.getCurrentPosition()) {
ctrack.draw(overlay);
document.getElementById('photo').setAttribute('src', data);
}
}
/*********** Code for stats **********/
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
document.getElementById('container').appendChild( stats.domElement );
// update stats on every iteration
document.addEventListener('clmtrackrIteration', function(event) {
stats.update();
}, false);
</script>
<script type="text/javascript">
(function() {
var streaming = false,
video = document.querySelector('#video'),
canvas = document.querySelector('#canvas'),
buttoncontent = document.querySelector('#buttoncontent'),
photo = document.querySelector('#photo'),
startbutton = document.querySelector('#startbutton'),
width = 320,
height = 0;
navigator.getMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
navigator.getMedia({
video: true,
audio: false
},
function(stream) {
if (navigator.mozGetUserMedia) {
video.mozSrcObject = stream;
} else {
var vendorURL = window.URL || window.webkitURL;
video.src = vendorURL.createObjectURL(stream);
}
video.play();
},
function(err) {
console.log("An error occured! " + err);
}
);
video.addEventListener('canplay', function(ev) {
if (!streaming) {
height = video.videoHeight / (video.videoWidth / width);
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
startbutton.addEventListener('click', function(ev) {
if(startbutton.innerText==="CAPTURE")
{
takepicture();
}
else
{
video.style.display = "block";
canvas.style.display = "none";
startbutton.innerText= "CAPTURE";
}
ev.preventDefault();
}, false);
})();
</script>
<script>
$(document).ready(function(){
$("#startbutton").click(function(){
$("#choosephoto").hide(1000);
});
});
</script>
Here is the code that i have tried how to save my captured images from webcam..
function takepicture(data_uri) {
video.style.display = "none";
canvas.style.display = "block";
startbutton.innerText= "RETAKE";
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(videoel, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
var data = canvas.toDataURL('image/webp');
document.getElementById('photo').setAttribute('src', data);
document.getElementById("two").value = data;
document.myForm.sub();
document.getElementById('capture').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="' + data_uri + '"/>';
document.myForm.sub();
}
//$
the above part of code is i have tried.Can anyone help Me please.
EDITED QUESTION AND CODE: if I now use the return statement in function move_background() and save the image inside the var imageObj as suggested, my code is still not working and plays sound2 both when inside and outside image (sound 3 is correctly played when outside canvas though), any ideas why?
</script>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid white;" onclick="myFunct()"></canvas>
<!-- audio source is specified later-->
<audio id="audio"></audio>
<style>
#myCanvas { position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto; }
</style>
<script>
var canvas=document.getElementById("myCanvas");
context = canvas.getContext('2d');
var imageObj = make_background();
function make_background()
{
img = new Image();;
img.src="img.gif";
img.id = "myImage";
img.onload = function(){
context.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2);
}
return img
}
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function myFunct() {
var audio = document.getElementById("audio");
// PLAY DIFFERENT SOUND IF ANSWER IS RIGHT OR WRONG
document.addEventListener("click", function(e){
if(e.target == imageObj){ // inside canvas and inside image
audio.src = "sound1.mp3";
audio.play();
}
else if (e.target === canvas && e.target !== imageObj) { // inside canvas but outside image
audio.src = "sound2.mp3";
audio.play();
}
else{
audio.src = "sound3.mp3";
audio.play();
}
// GENERATE RANDOM LOCATION
var x = Math.floor(Math.random()*300);
var y = Math.floor(Math.random()*300);
var obj = document.getElementById("myCanvas");
obj.style.top = x + "px";
obj.style.left = y + "px";
obj.style.bottom = x - "px";
obj.style.right = y - "px";
},false);
}
</script>
ORIGINAL QUESTION AND CODE: I have a rect canvas and an image in its center. I would like to play a different audio file when a click is inside the canvas (but outside the image) and when the click is inside the image.
This is what I have for now
<canvas id="myCanvas" width="400" height="400" style="border:1px solid white;" onclick="myFunct()"></canvas>
<!-- audio source is specified later-->
<audio id="audio"></audio>
<script>
var canvas=document.getElementById("myCanvas");
context = canvas.getContext('2d');
make_background();
function make_background()
{
img = new Image();
img.src = 'img.gif';
img.onload = function(){
context.drawImage(img, 100, 100);
}
}
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function myFunct() {
var audio = document.getElementById("audio");
var canv = document.getElementById("myCanvas");
document.addEventListener("click", function(e){
if( inside canvas and inside img){
audio.src = "sound1.mp3";
audio.play();
}
else if (inside canvas and outside img) {
audio.src = "sound2.mp3";
audio.play();
}
else{
audio.src = "sound3.mp3";
audio.play();
}
},false);
}
</script>
To start a word of caution myFunct call will bind multiple click events to your document every time you click the canvas. I have edited the fiddle to achieve something that you are looking for. Please let me know if that helps.
<canvas id="myCanvas" width="400" height="400" style="border:1px solid white;" onclick="myFunct(event)"></canvas>
<!-- audio source is specified later-->
<audio id="audio"></audio>
<script>
var canvas=document.getElementById("myCanvas");
context = canvas.getContext('2d');
var imageObj = make_background();
function make_background()
{
img = new Image();
img.src = 'http://placehold.it/100x100';
img.onload = function(){
context.drawImage(img, 100, 100);
}
return img;
}
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function myFunct(e) {
var audio = document.getElementById("audio");
var canv = document.getElementById("myCanvas");
if( e.clientX > 100 && e.clientX < 100 + imageObj.width && e.clientY > 100 && e.clientY < 100 + imageObj.height){
console.log('inside image and canvas');
//audio.src = "sound1.mp3";
//audio.play();
}
else if (e.clientX > 400 || e.clientY > 400) {
// outside canvas
console.log('outside canvas');
//audio.src = "sound2.mp3";
//audio.play();
}
else{
console.log('inside canvas but outside image');
//audio.src = "sound3.mp3";
//audio.play();
}
}
</script>
In this piece of code I have video.currentTime = {value}
And it works fine.
But when I'm trying to reload the page by pressing Crtl+Shift+R it sets video.currentTime to 0, no matter when on the progress bar I clicked.
Why is that?
window.addEventListener('load', function(){
var video = document.getElementById('video');
var playButton = document.getElementById('play-button');
var pbar = document.getElementById('pbar');
var update;
var pbarContainer = document.getElementById('pbar-container');
video.load();
video.addEventListener('canplay', function(){
playButton.addEventListener('click', playOrPause, false);
pbarContainer.addEventListener('click', skip, false);
}, false);
var skip = function(ev) {
var mouseX = ev.pageX - pbarContainer.offsetLeft;
var width = window.getComputedStyle(pbarContainer).getPropertyValue('width');
width = parseFloat(width.substr(0, width.length - 2));
video.currentTime = (mouseX/width)*video.duration;
};
var updatePlayer = function() {
var percentage = (video.currentTime/video.duration)*100;
pbar.style.width = percentage + '%';
if(video.ended) {
window.clearInterval(update);
playButton.src = 'images/replay.png';
}
};
var playOrPause = function(){
if(video.paused) {
video.play();
playButton.src = 'images/pause.png';
update = setInterval(updatePlayer, 30);
} else {
video.pause();
playButton.src = 'images/play.png';
window.clearInterval(update);
}
};
//video.addEventListener('click', playOrPause(playButton), false);
}, false);
Refreshing your page stops all execution of your code and resets all your variables, basically starting you from the beginning.
If you want variables to remain even after refreshing the page then set the localStorage and your values will be saved on the browser. You can find them if you open your developer tools in the Resources section under localStorage:
localStorage.setItem(video.currentTime,value)
To retrieve it, you'll have to use
localStorage.getItem(video.currentTime,value)
I am using an HTML5 Video on my website, with certain other codes that basically makes usability more customized.
The video is intended to play when in view and pause when not in view. Additionally it also has a play and pause button that comes into view when the mouse hovers on the video.
At the end of the video it turns into an image because by default the html5 video would just turn to blank.
The problem is that the image turns up in the end, but the play/pause continue to appear on hover and function as play pause but only audio. You cannot see the video.
I originally wanted it to just show the picture. But would prefer to have the play pause turn into a restart button if the video ends.
I tried looking for something that would fit my existing setup, but I am not sure how to make it happen and which of these codes would I play with.
Here is a link for the site
http://minhasdistillery.com/blumersmoonshine/
<section id="feature">
<div id="trail">
<div id="videocontrol">
<a id="play-pause" class="play"><img src="images/pause.png"/></a>
</div>
<video id="video_background" preload="auto" volume="5"><!--or turn on loop="loop"-->
<source src="videos/video.webm" type="video/webm">
<source src="videos/video.mp4" type="video/mp4">
<source src="videos/video.ogv" type="video/ogg ogv">
</video>
<img id="image_background" src="images/blumer.jpg" width="100%" height="100%" />
</div><!--trail-->
</section><!--feature-->
Javascript that brings up play/pause button
<script>
window.onload = function() {
var video = document.getElementById("video_background");
var playButton = document.getElementById("play-pause");
playButton.addEventListener("click", function() {
if (video.paused == true) {
video.play();
playButton.innerHTML = "<img src='images/pause.png'/>";
} else {
video.pause();
playButton.innerHTML = "<img src='images/play.png'/>";
}
});
}
</script>
The code sets the video to play on when visible and pause otherwise
<script>
//play when video is visible
var videos = document.getElementsByTagName("video"), fraction = 0.8;
function checkScroll() {
for(var i = 0; i < videos.length; i++) {
var video = videos[i];
var x = 0,
y = 0,
w = video.offsetWidth,
h = video.offsetHeight,
r, //right
b, //bottom
visibleX, visibleY, visible,
parent;
parent = video;
while (parent && parent !== document.body) {
x += parent.offsetLeft;
y += parent.offsetTop;
parent = parent.offsetParent;
}
r = x + w;
b = y + h;
visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));
visible = visibleX * visibleY / (w * h);
if (visible > fraction) {
video.play();
} else {
video.pause();
}
}
}
window.addEventListener('scroll', checkScroll, false);
window.addEventListener('resize', checkScroll, false);
//check at least once so you don't have to wait for scrolling for the video to start
window.addEventListener('load', checkScroll, false);
checkScroll();
</script>
This one adds the photo in the end.
<script>
var video = document.getElementById('video_background');
var wrapper = document.getElementById('wrapper');
var image = document.getElementById('image_background');
video.addEventListener('ended', function() {
video.style.display = 'none';
image.style.display = 'inline';
}, false);
</script>
A JSBin of the same issue is here
JSBin For Issue
as you will see at the end of the video it will continue to show pause and play and will only play audio.
How do I get it to read that the video ended and switch the button to "replay"
Initially video display style is block and image display style is none.
Video ended event handler sets video display to none and image display to inline.
You can check video display style in button click event handler and toggle it:
playButton.addEventListener(
'click',
function(event) {
if (video.style.display === 'none') {
image.style.display = 'none';
video.style.display = 'block';
}
...
},
false
);
As an alternative add boolean flag which is intially set to false, on video ended event set it to true:
var needReplay = false;
video.addEventListener(
'ended',
function() {
...
needReplay = true;
},
false
);
playButton.addEventListener(
'click',
function(event) {
if (needReplay) {
image.style.display = 'none';
video.style.display = 'block';
needReplay = false;
}
...
},
false
);
Demo