Add 2 Webcam in one page with WebcamJS - javascript

I'm trying to add 2 or multiple webcam input with webcam.js from jhuckaby. But only one will works perfectly. And i'm following this tutorial
https://pixlcore.com/demos/webcamjs/demos/preview.html
Here's my javascript code:
Webcam.set({
width: 100,
height: 100,
force_flash: true,
image_format: 'jpeg'
});
// CAMERA 1
Webcam.attach('#my_camera');
function preview_snapshot() {
Webcam.freeze();
document.getElementById('pre_take_buttons').style.display = 'none';
document.getElementById('post_take_buttons').style.display = '';
}
function cancel_preview() {
Webcam.unfreeze();
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
}
function save_photo() {
// actually snap photo (from preview freeze) and display it
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h5>Profil anda:</h5>' +
'<img src="'+data_uri+'"/>';
// swap buttons back
document.getElementById('pre_take_buttons').style.display = '';
document.getElementById('post_take_buttons').style.display = 'none';
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydataProfil').value = raw_image_data;
} );
}
// Camera 1 END
// CAMERA 2
Webcam.attach('#my_camera_ktp');
function preview_snapshot_ktp() {
Webcam.freeze();
document.getElementById('pre_take_buttons_ktp').style.display = 'none';
document.getElementById('post_take_buttons_ktp').style.display = '';
}
function cancel_preview_ktp() {
Webcam.unfreeze();
document.getElementById('pre_take_buttons_ktp').style.display = '';
document.getElementById('post_take_buttons_ktp').style.display = 'none';
}
function save_photo_ktp() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results_ktp').innerHTML =
'<h5>Profil anda:</h5>' +
'<img src="'+data_uri+'"/>';
// swap buttons back
document.getElementById('pre_take_buttons_ktp').style.display = '';
document.getElementById('post_take_buttons_ktp').style.display = 'none';
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydataProfilKTP').value = raw_image_data;
} );
}
And this is my camera 1 HTML code:
<center>
<div id="my_camera"></div>
<br>
<div id="pre_take_buttons">
<input type=button value="Take Foto" onClick="preview_snapshot()">
</div>
</center>
<div id="post_take_buttons" style="display:none" class="text-center">
<input type=button value="< Take again" onClick="cancel_preview()">
<input type=button value="Save >" onClick="save_photo()">
</div>
Camera 2 HTML code:
<center>
<div id="my_camera_ktp"></div>
<br>
<div id="pre_take_buttons_ktp">
<input type=button value="Take foto KTP" onClick="preview_snapshot_ktp()">
</div>
</center>
<div id="post_take_buttons_ktp" style="display:none" class="text-center">
<input type=button value="< take again" onClick="cancel_preview_ktp()">
<input type=button value="Save >" onClick="save_photo_ktp()">
</div>
The problem is if i use camera 1, camera 2 does'nt work, if i use camera 2 then camera 1 does'nt work. Function's name and id already different and unique, Camera 1 and 2 has same function and html, the difference only function's name and id. And then i use inspect element on my page, show me an error like this
Uncaught TypeError: this.getMovie(...)._snap is not a function
Any answer?

I think you can't achieve this by using that library. However, I solved this by using only javaScript. Here what you need to do.
HTML:
<div style="width: 100%;text-align:center;">
<video id="myCamer2" width="150" height="150" autoplay></video>
</div>
Script:
<script>
// second camera
let video = document.querySelector("#myCamer2");
let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
video.srcObject = stream;
</script>
You can learn more about this from https://usefulangle.com/post/352/javascript-capture-image-from-camera
and https://www.studytonight.com/post/capture-photo-using-webcam-in-javascript here.

Related

How to assign a file input to another file input?

Strange question, I know. The main issue here is I am using a cool tool called cropit. In this, we upload one image, get a preview, and the process it however we want.
HTML:
<div align="center" id="image-cropper1">
<!-- This is where user selects new image -->
<label class="btn btn-success btn-file">Upload Photo<input type="file" class="cropit-image-input"/></label><br><br>
<!-- This is where the preview image is displayed -->
<label><div class="cropit-preview"><img class="prepic" src="preloadimage.jpg"></label>
<!-- Here I process the image -->
<button type="button" id="image1pick" class="btn btn-primary" data-dismiss="modal" disabled>OK</button></div>
JQuery:
$('#image-cropper1').cropit();
$('#image-cropper1').change(function() {
$('#image1pick').prop('disabled', false);
});
$('#image1pick').click(function() {
imageData1 = $('#image-cropper1').cropit('export', {originalSize: true});
$.post('somephp.php', { imageData1: imageData1 }, function() { $('#image1pick').data('clicked', true) })
});
Now, what I want to achieve is to add another <input type="file"/> button that uploads 6 images at once and get them on 6 different ".cropit-preview" divs. It's essential, since the user can zoom and rotate the image in the preview. Is there a way to get multiple files and add them in every preview div in this given tool structure?
EDIT:
Please look at the doc: http://scottcheng.github.io/cropit/
The problem is the structure. Let's say I have three different croppers. The structure would look like this:
JQuery:
$('#image-cropper1').cropit();
$('#image-cropper2').cropit();
$('#image-cropper3').cropit();
HTML:
<!-- Cropper No 1 -->
<div id="image-cropper1">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>
<!-- Cropper No 2 -->
<div id="image-cropper2">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>
<!-- Cropper No 3 -->
<div id="image-cropper3">
<input type="file" class="cropit-image-input" />
<div class="cropit-preview"></div>
</div>
As you see here each file input and preview div is inside the numbered div and i coupled. But now I want to have an input, which upload three images at the same time and fits to every image-preview in every numbered div. How can I achieve this?
To copy the file selection from one input to another, you can do something like:
var file1 = document.querySelector('#image-cropper1>input[type=file]');
var file2 = document.querySelector('#image-cropper2>input[type=file]');
file2.files = file1.files;
For <input type="file"> elements, the files attribute points to a FileList object, described here.
Try this:
$("#destinationFileInput").prop("files",$("#sourceFileInput").prop("files"));
I would do something like this:
//external.js
var doc, C;
$(function(){
doc = document;
C = function(tag){
return doc.createElement(tag);
}
$('#upload').change(function(ev){
var out = $('#output'), fs = this.files, fl = fs.length;
if(fl > 6){
console.log('Too many files');
}
else{
var dv = C('div');
$.each(fs, function(i, v){
var fr = new FileReader, ig = C('img'), cv = C('canvas'), z = cv.getContext('2d');
fr.onload = function(ev){
ig.onload = function(){
cv.width = this.width; cv.height = this.height; z = cv.getContext('2d'); z.drawImage(this, 0, 0); dv.append(cv);
}
ig.src = ev.target.result;
}
fr.readAsDataURL(v);
});
out.append(dv);
}
});
$('#send').click(function(){
var fd = new FormData;
$('canvas').each(function(i, e){
e.toBlob(function(b){
var bf = new FileReader;
bf.onloadend = function(){
fd.append('image_'+i, bf.result); fd.append('count', i+1);
}
bf.readAsArrayBuffer(b);
});
});
/*
$.post('yourPage.php', fd, function(response){
response comes back here
test on PHP on a separate PHP page yourPage.php
<?php
if(isset($_POST['image_0'], $_POST['count'])){
for($i=0,$c=$_POST['count']; $i<$c; $i++){
$ig = 'image_'.$i;
if(isset($_POST[$ig])){
file_put_contents("resricted/$ig.png", $_POST[$ig]);
}
}
}
?>
});
*/
});
});
/* external.css */
html,body{
margin:0; padding:0;
}
.main{
width:980px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<link type='text/css' rel='stylesheet' href='external.css' />
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form>
<input type='file' multiple='multiple' id='upload' />
<input type='button' id='send' value='Send to Server' />
</form>
<div id='output'></div>
</div>
</body>
</html>
Just assign source input tag file to the other one like below:
If I have two input tags: source and target.
<input id="source" type="file" name="file" accept=".jpg,.jpeg,.png" multiple="multiple" aspect="1" >
<input id="target" type="file" name="file" accept=".jpg,.jpeg,.png" multiple="multiple" aspect="1" >
let source = document.getElementById("source");
let target = document.getElementById("target");
source.files = target.files;
Thanks for Ourobonus's hint.
If you only want to show image's thunmbnail, you can reference
https://developer.mozilla.org/en-US/docs/web/api/file_api/using_files_from_web_applications.

I need help getting autoplay to work via [getElementById]

My code: https://jsfiddle.net/m656xw8s/24/
I've been trying to get autoplay to work, can someone show me what the correct code would be? Using the code I provided. Using [getElementById]
var player = document.getElementById('player').autoplay; document.getElementById('player').innerHTML = true;
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
var player = document.getElementById('player').autoplay;
document.getElementById('player').innerHTML = true;
var player = document.getElementById('player').volume='1.0';
var button = document.getElementById('playButton');
var player = document.getElementById('player');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>
Set the autoplay then load.
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_av_prop_autoplay
Update:
document.getElementById('playButton').addEventListener('click', autoPlayToggle);
document.getElementById('autovolume_range').addEventListener('change', changeVol);
//Only getElementById once!
var player = document.getElementById("player");
var autoplaytext = document.getElementById("autoplay_text");
var autovolumetext = document.getElementById("autovolume_range");
//Boolean from localstorage to keep state of the player
var autoPlayOn = autoplaytext.value = (localStorage.getItem("keepAutoPlay") === "true");
var setVolumeOn = autovolumetext.value = parseFloat(localStorage.getItem("keepVolume"));
player.volume = setVolumeOn;
player.autoplay = autoPlayOn;
player.load();
//Force play if it dosen't autoplay after refresh
if (player.autoplay == true) {
player.play();
} else {
player.pause();
}
//Function
//When the user refreshes the page it will keep the autoplay state
function autoPlayToggle() {
if (player.paused) {
player.play();
player.autoplay = true;
} else {
player.pause();
player.autoplay = false;
}
//Show the state in a text box
autoplaytext.value = player.autoplay;
//Save updated state to your local disk
localStorage.setItem("keepAutoPlay", autoplaytext.value);
}
//Save state of volume
function changeVol() {
player.volume = this.value;
localStorage.setItem("keepVolume", this.value);
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;">
</button>
<audio id="player" style="display:none;" >
<source src='http://hi5.1980s.fm/;' type='audio/mpeg'/>
</audio>
AutoPlay: <input id="autoplay_text" />
AutoVolume: <input type="range" step="0.1" min="0.0" max="1.0" id="autovolume_range" />
https://jsfiddle.net/LeroyRon/dtnrdjd5/
You only need to add attribute auto play to your audio tag see the updated code below; Based on your code you are redeclaring player multiple times see the updated code below. Your auto play is triggered on button click based on your code, you may want to separate the javascript codes to the button and just trigger a method indicated on your button click event.
You will need to use removeAttribute to remove the autoplay from your audio element. I added the code on how to do it below.
//player declared outside of the audioPlay method to make it accessible inside the audioPlay method
var player = document.getElementById('player');
//auto play set outside playAudio method outside of the button click event method
player.setAttribute('autoplay', '');
//to set autoplay false uncomment the code below
//player.removeAttribute('autoplay');
//playAudio is triggered on button click event
function playAudio(){
player.setAttribute('volume', 1.0);
var button = document.getElementById('playButton');
if (player.paused) {
playButton.style.backgroundColor = 'red';
player.play();
} else {
playButton.style.backgroundColor = 'red';
player.pause();
}
}
<button id="playButton" style="border:none; width: 200px; height: 200px; cursor: pointer; font-family:Tahoma; font-weight: bold;font-size:14px; background-color:red;color:blue;" onclick="
playAudio()">
</button>
<audio id="player" style="display:none;">
<source src='http://hi5.1980s.fm/;' type='audio/mpeg' />
</audio>

How to Stop or Pause JavaScript Animation?

I had a simple JS script which takes an array of images and display them as an animation by clicking a start button.
I am trying to stop the animation by clicking on the stop button (stop on the current image of the animation), which does not work.
I will appreciate any help. Thanks
<script type="text/javascript">
var images = new Array("unc_prop_1dim_x1.jpg", "unc_prop_1dim_x2.jpg",
"unc_prop_1dim_x3.jpg", "unc_prop_1dim_x4.jpg", "unc_prop_1dim_x5.jpg");
var nextImage = 0; //Index for nextImage
var timeout = 400; //In milliseconds
function animation() {
document.ani.src = images[nextImage];
nextImage++;
if (nextImage==images.length) {
nextImage = 0;
}
setTimeout("animation();", timeout);
};
function stopAnimation() {
ani.stop();
}
document.querySelector('#stop').onclick = function() {
stopAnimation();
};
</script>
<body>
<div id="main" style="width: 700px; height: 500px;">
<img src="unc_prop_1dim_x1.jpg" name="ani"/>
</div><br>
<input type="button" id="start" onclick="animation();" value="Start Animation">
<input type="button" id="stop" value="Stop!">
</body>

how to open a image in lightbox?

I want to open a image in lightbox like in this address using JavaScript.
this code i am using in HTML it works fine. but i want to use this code in JavaScript function.
<div class="imageRow">
<div class="single">
<img alt="" src="url" />
</div>
</div>
How to write it in JavaScript.
for example this code open a image in new window.i want code like this to open a image in Lightbox2 using classes that are in upper HTML code.
<script type="text/javascript">
function onListPhotoClicked(event) {
var position = event.getPosition();
var photo=event.getPhoto();
if(photo){
MaximizeWindow(window.open('http://static.panoramio.com/photos/original/'+photo.getPhotoId()+'.jpg'));
}
}
function MaximizeWindow(hWnd){
hWnd.moveTo(0,0);
hWnd.resizeTo(screen.width, screen.height);
}
panoramio.events.listen(
attr_ex_photo_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked(e); });
</script>
this code open a image in new tab.but i want that this code open image in lightbox2.
i am new in programming.please tell me in detail by writing code.
this is code of a panoramio.com widget.
<div>
<img border="0" height="0" src="http://3.bp.blogspot.com/-EHT3COGzPHY/UnTXKACCkMI/AAAAAAAAAuI/KXnLjT-6ovk/s1600/98289201.jpg" width="0" /></div>
<script src="http://www.panoramio.com/wapi/wapi.js?v=1" type="text/javascript"></script>
<style type="text/css">
#div_attr_ex .panoramio-wapi-images {
background-color: transparent;
}
</style>
<br />
<div id="div_attr_ex" style="float: center; margin: 5px 10px;">
<div id="photo_widget_id_a11">
</div>
<div id="photo_widget_id_b11">
</div>
<div id="photo_widget_id_c11">
</div>
</div>
<script type="text/javascript">
var sand = {'set': panoramio.PhotoSet.RECENT };
var sandRequest = new panoramio.PhotoRequest(sand);
var attr_ex_photo_options = {
'width': 600,
'height': 480,
'disableDefaultEvents': [panoramio.events.EventType.PHOTO_CLICKED],
'attributionStyle': panoramio.tos.Style.HIDDEN};
var attr_ex_photo_widget = new panoramio.PhotoWidget(
'photo_widget_id_a11', sandRequest, attr_ex_photo_options);
var attr_ex_list_options = {
'width': 600,
'height': 110,
'columns': 6,
'rows': 1,
'croppedPhotos': true,
'disableDefaultEvents': [panoramio.events.EventType.PHOTO_CLICKED],
'orientation': panoramio.PhotoListWidgetOptions.Orientation.HORIZONTAL,
'attributionStyle': panoramio.tos.Style.HIDDEN};
var attr_ex_list_widget = new panoramio.PhotoListWidget(
'photo_widget_id_b11', sandRequest, attr_ex_list_options);
var attr_ex_attr_options = {'width': 300};
var attr_ex_attr_widget = new panoramio.TermsOfServiceWidget(
'photo_widget_id_c11', attr_ex_attr_options);
function onListPhotoClicked2(event) {
var position = event.getPosition();
var photo=event.getPhoto();
document . apple . banana . value = position;
if(photo){
MaximizeWindow(window.open('http://static.panoramio.com/photos/large/'+photo.getPhotoId()+'.jpg'));
}
}
function MaximizeWindow(hWnd){
hWnd.moveTo(0,0);
hWnd.resizeTo(screen.width, screen.height);
}
panoramio.events.listen(
attr_ex_photo_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked2(e); });
function onListPhotoClicked(event) {
var position2 = attr_ex_list_widget.getPosition();
attr_ex_list_widget.setPosition(position2+1);
var position = event.getPosition();
if (position !== null) attr_ex_photo_widget.setPosition(position);
document . apple . banana . value = position;
}
panoramio.events.listen(
attr_ex_list_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked(e); });
attr_ex_photo_widget.enablePreviousArrow(true);
attr_ex_photo_widget.enableNextArrow(true);
attr_ex_photo_widget.setPosition(0);
attr_ex_list_widget.setPosition(0);
function increase()
{
var temp = parseInt (document . apple . banana . value);
if (isNaN (temp))
return;
if (temp>=0 )
{
attr_ex_photo_widget.setPosition(temp);
attr_ex_list_widget.setPosition(temp);
document . apple . banana . value = temp;
}
else
{
attr_ex_photo_widget.setPosition(0);
attr_ex_list_widget.setPosition(0);
document . apple . banana . value = 0;
}
}
function startDownload()
{
var photo3=attr_ex_photo_widget.getPhoto();
var url='http://static.panoramio.com/photos/original/'+photo3.getPhotoId()+'.jpg';
window.open(url);
}
</script>
<form name="apple">
<input max="10000" maxlength="4" min="0" name="banana" size="4" type="number" />
<input onclick="increase ();" type="button" value="View" /></form>
<button onclick="startDownload()">Download</button>

Mouse listeners not working with innerHTML and images in a gallery

Basically, for this snippet of code, I would like to get the picture to show when clicked on, as shown by my onmousedown function. But for some reason, when I click on the picture, it does not show the picture that I have called in my server() function. In addition to that, my counters (the buttons) do not work as they are supposed to (add and subtract).
<!-- HTML header and stylesheets -->
memory = 0;
hdd = 0;
usb = 0;
server = "";
function allInOne()
{
document.getElementById("memory").innerHTML = memory;
document.getElementById("hdd").innerHTML = hdd;
document.getElementById("usb").innerHTML = usb;
}
function server();
{
div = document.getElementById("server");
div.innerHTML = "<img src = 'server1.png' />";
}
<!-- omitted some HTML -->
<span> Memory (GB) <span>
<button onmousedown="allInOne();memory++">+</button>
<article id = "memory">0</article>
<button onmousedown="allInOne();memory--">-</button>
<br />
<span> HDD (GB) </span>
<button onmousedown="allInOne();hdd++">+</button>
<article id = "hdd">0</article>
<button onmousedown="allInOne();hdd--">-</button>
<br />
<span> USB Ports </span>
<button onmousedown="allInOne();usb++">+</button>
<article id = "usb">0</article>
<button onmousedown="allInOne();usb--">-</button>
<br />
<span class = "button" onmousedown="mac"> Mac OS X </span>
<span class = "button" onmousedown="linux"> Linux </span>
<span class = "button" onmousedown="windows"> Windows </span>
<br />
<img src = "server1.png" onmouseover="server();" />
<img src = "laptop.jpg" />
<img src = "0009-03_lenovo_pc.jpg"/>
<!-- some more HTML below -->
If anyone could help it would be greatly appreciated.
Okay here you go.
<script type = "text/javascript">
memory = 0;
hdd = 0;
usb = 0;
server = "";
function allInOne()
{
document.getElementById("memory").innerHTML = memory;
document.getElementById("hdd").innerHTML = hdd;
document.getElementById("usb").innerHTML = usb;
}
function server1()
{
var div_server = document.getElementById("server");
div_server.innerHTML = "<img src = 'i_icon.gif' />";
}
</script>
removed a ; which was present after function server()
renamed the method to server1() since a variable is there named server.
change closing tag <span> to </span>
moved all the ++ and -- operation before calling the methid allInOne().
changed all the event to onclick. I have used a different image from system.
and it working fine. please test now
It's better and more efficient to add event listeners from your javascript. Every onmousedown, onclick etc. triggers an eval action. There are 2 ways to add an event listener to a HTML element: [element].on[action] = [some function] or using the addEventListener/attachEvent method of a html element.
Have a look at this jsfiddle example to see if you can apply that to your code
Try the following
<!DOCTYPE html>
<html>
<head>
<title> Javascript </title>
<link rel = "stylesheet" type = "text/css" href = "css.css">
<script type = "text/javascript">
memory = 0;
hdd = 0;
usb = 0;
server = "";
function allInOne()
{
document.getElementById("memory").innerHTML = memory;
document.getElementById("hdd").innerHTML = hdd;
document.getElementById("usb").innerHTML = usb;
}
function server()
{
div = document.getElementById("server");
div.innerHTML = "<img src = 'server1.png' />";
}
function changeText(id)
{
if(id == 'mac')
{
txt = document.getElementById("mac");
txt.innerHTML = "mac";
}
else if(id =='linux' )
{
txt = document.getElementById("linux");
txt.innerHTML = "linux";
}
else
{
txt = document.getElementById("windows");
txt.innerHTML = "windows";
}
}
</script>
</head>
<body>
<div>
<span> Memory (GB) <span>
<button onmousedown="allInOne();memory++">+</button>
<article id = "memory">0</article>
<button onmousedown="allInOne();memory--">-</button>
<br />
<span> HDD (GB) </span>
<button onmousedown="allInOne();hdd++">+</button>
<article id = "hdd">0</article>
<button onmousedown="allInOne();hdd--">-</button>
<br />
<span> USB Ports </span>
<button onmousedown="allInOne();usb++">+</button>
<article id = "usb">0</article>
<button onmousedown="allInOne();usb--">-</button>
<br />
<span class = "button" onmousedown="changeText(this.id);" id="mac"> Mac OS X </span>
<span class = "button" onmousedown="changeText(this.id);" id="linux"> Linux </span>
<span class = "button" onmousedown="changeText(this.id);" id="windows"> Windows </span>
<br />
<img src = "server1.png" onmouseover="server();" />
<img src = "laptop.jpg" />
<img src = "0009-03_lenovo_pc.jpg"/>
<br />
<div id = "server"></div>
</div>
</body>
</html>
You did one mistake while declaring the function with ; like the following
function server();
{
}
You need to remove the semicolon currently on the end of the line:
function server();
Regarding the buttons: you don't actually say what is wrong with your add/subtract button behaviour but I'm guessing the problem is that you update the display first via the allInOne() function and then increment or decrement after that.
Instead of saying:
onmousedown="allInOne();memory++"
Try:
onmousedown="memory++;allInOne();"
// or, unless you have a specific reason for using mousedown rather than click
onclick="memory++;allInOne();"

Categories