error "Webcam.js Error: Webcam is not loaded yet" - javascript

Hello i am setting up a selfie "photobooth". Everything works like fine but i found a bug and dont't find a solution.
I'll explain the function: I have a webcam that shows live-video. If i push the "s"-key it takes a picture and freezes it to the screen for 15 seconds. Wile it is showing the frozen image i can push "s"-key again for stopping the freez and start again with the live-video. Otherwise it jumps back to live-video after 15 seconds. Till here everything works perfect.
Now my problem: If i push the "s"-key more often while the freezed image is showing. It clears the frozen image and shows my background-image giving my a error-box with this message: "Webcam.js Error: Webcam is not loaded yet"
How can this be solved?
Thanks for any help!
Here is my code:
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Emotionen Fotobooth</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<img src="bg.jpg" id="bg" alt="">
<div id="foto">
<div id="my_camera"></div>
<!-- <input type=button class=anybutton value="Take Snapshot" onClick="take_snapshot()"> -->
<!-- Webcam.min.js -->
<script type="text/javascript" src="webcamjs/webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
let seconds = 15 // time to show image
// Configure a few settings and attach camera
let propwidth = 1600 // width of webcam window
Webcam.set({
width: propwidth,
height: (propwidth/16)*9,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
// preload shutter audio clip
//var shutter = new Audio();
//shutter.autoplay = true;
//shutter.src = 'shutter.mp3';
//document.addEventListener('DOMContentLoaded', (event) => {
document.addEventListener('keydown', function(event) {
if (event.code == 'KeyS' ) {
take_snapshot()
}
});
function take_snapshot() {
// play sound effect
// shutter.play();
// take snapshot and get image data
Webcam.snap( function(data_uri) {
document.getElementById('my_camera').innerHTML = '<img src="'+data_uri+'"/>';
show_snapshot();
});
}
function show_snapshot(){
// display results in page
document.addEventListener('keydown', function(event) {
if (event.code == 'KeyS' ) {
window.location.href = window.location.href;
}
});
var showTimer = setInterval(function(){
clearInterval(showTimer);
window.location.href = window.location.href;
}, seconds*1000);
}
//})
Webcam.attach( '#my_camera' );
</script>
</div>
</body>
</html>

Related

window.matchMedia not works in iframe

I'm detecting device orientation using window.matchMedia. The following code works as intended - every orientation change is logged to console with correct value:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Test App</title>
</head>
<body>
<script type="application/javascript">
let isIframe= () => {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
let onOrientationChange = () => {
const isLandscape = window.matchMedia("(orientation: landscape)").matches;
console.log("Event: " + (isIframe() ? "Iframe " : "") + "landscape:" + isLandscape);
}
let mediaQueryList = window.matchMedia("(orientation: landscape)");
console.log("Onload: " + (isIframe() ? "Iframe " : "") + "landscape:" + mediaQueryList.matches);
mediaQueryList.addListener(onOrientationChange);
</script>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">Hello World in Iframe</div>
</body>
</html>
But when I run that page in iframe, callback registered using addListener is not fired. In iframe, I only get singular log line - Onload: Iframe landscape:true, regardless of the device orientation.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root">Hello World</div>
<iframe id="game" src="iframeContent.html" frameborder="0" style="width: 960px; height: 600px;"></iframe>
</body>
I'm using addListener instead of addEventListener, because the second one function is not working on all Safari versions.
Tested on Safari 14 and on Dev Tools of Chrome and Firefox.
My question is - why addListener callback is not invoked in iframe.
Thank you.
If the iframe does not get it's size to change because it has fixed width and height, thus resize related events cannot be triggered inside it including MediaQueryList events regarding orientation.
You can do two things to get this working; you can make your iFrame width and height to be 100%, or you can let the media query detection code inside the main window and pass the orientation state using postMessage when it triggers a change event.
1) Changing iFrame size to 100% so it resizes when landscape/portrait orientation event triggers
In the main page, make the body full height and the iframe full width/height (using CSS).
body {
height: 100vh;
margin: 0;
}
iframe {
width: 100%;
height: 100%;
}
Live example that you can test: https://zikro.gr/dbg/so/65704468/
2) Media query detection on the main page and use postMessage to send a message to iFrame when orientation event triggers
index.html:
<iframe src="iframe.html"></iframe>
<script>
let iframe = document.querySelector('iframe');
let onOrientationChange = () => {
iframe.contentWindow.postMessage({
isLandscape: window.matchMedia("(orientation: landscape)").matches
}, '*');
}
iframe.addEventListener('load', onOrientationChange);
const mediaQueryList = window.matchMedia("(orientation: landscape)");
mediaQueryList.addListener(onOrientationChange);
</script>
iframe.html:
<script>
window.addEventListener("message", (event) => {
if (event.data.isLandscape) {
console.log('iFrame Landscape');
} else {
console.log('iFrame Portrait');
}
});
</script>
Live example that you can test: https://zikro.gr/dbg/so/65704468/pm/

Audiocontext is not playing any sound

as a follow-up on this post: How to rapidly play multiple copies of a soundfile in javascript I created a small demo page to illustrate the core of my problem.
My goal is to rapidly play the same audiofile over and over again while a user holds down a button, without crashing the browser ;-) (second line in the fiddle)
My initial method uses clone node to create multiple audio objects in the DOM. This works actually fine in chrome and edge, but safari and firefox run into problems after a while. This leads to dis-synchronized audios, and audios that keep on starting after the user has released the button.
So Codebreaker007 proposed to use audio-context instead, which resulted in a couple of different problems. Chrome replies:
The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.
Chrome and firefox don't play the audio file. I then followed the google guide and got at least the error messages to be gone, but still no audible audio. Using the web audio plugin for chrome I could at one point see that the audio nodes are being created correctly. How can I make them audible? How can I get the Audio Context to start?
I think I'm quite close to the solution, so let's fix this together.
<!doctype html>
<html class="h-100" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Test</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
AudioContext:true;
var clickingBuffer = null;
var timer
var inStart = 0
var inStop = 0
var timer = null
var type = ""
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
// =========== Variant 1: Clone Node ========== //
var sound = new Audio("https://sounds4email.com/wav/hellobaby.mp3");
sound.preload = 'auto';
sound.load();
function triggersound(){
console.log("triggerSound")
var click=sound.cloneNode();
click.volume=1;
click.play();
}
// =========== Variant 2: AudioContext ========== //
function loadClickSound(url) {
console.log("loading sound")
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
if (!buffer) {
console.log('Error decoding file data: ' + url);
return;
}
clickingBuffer = buffer;
});
request.onerror = function() {
console.log('BufferLoader: XHR error');
};
console.og("sound buffered")
request.send();
};
}
function playSound(buffer, time, volume) {
console.log("playSound")
context.resume().then(() => {
var source = context.createBufferSource(); // creates a sound source
source.buffer = buffer; // tell the source which sound to play
source.connect(context.destination); // connect the source to the context's destination (the speakers)
var gainNode = context.createGain(); // Create a gain node
source.connect(gainNode); // Connect the source to the gain node
gainNode.connect(context.destination); // Connect the gain node to the destination
gainNode.gain.value = volume; // Set the volume
source.start(time); // play the source at the deisred time 0=now
console.log('Playback resumed successfully');
});
}
// =========== RAPID FIRE ========== //
function stop() {
console.log("stop")
inStop = 1
}
// Initializing the spinning sequence. Blocking other user interaction
function start(tp) {
type = tp
console.log("active")
context.resume().then(() => {
console.log('Playback resumed successfully');
if (null === timer) {
timer = setInterval(timerCallback, 200)
inStart = 1
}
});
}
/**
* Timer callback
*/
function timerCallback() {
console.log(type + " " + inStart + " " + inStop)
if (inStart) {
if(type==="node"){
triggersound()
} else if(type==="context"){
playSound(clickingBuffer, 0, 1)
}
}
if (inStop) {
inStop = 0
clearTimeout(timer)
timer = null
console.log("stopped")
}
}
// =========== DOC READY ========== //
$( document ).ready(function() {
console.log( "ready!" );
// You call with in your document ready
loadClickSound("https://sounds4email.com/wav/hellobaby.mp3");
// Fix up prefixi
});
// =================================================================================//
</script>
</head>
<body class="d-flex flex-column align-content-center align-items-center justify-content-center w-100 h-100" >
<div class="row p-1 w-100">
<div class="col">
Click once:
</div>
<button id="clickNode" style="width: 100px; height: 100px;" class="col m-1" onclick="triggersound()">
Clone Node
</button>
<button id="clickContext" style="width: 100px; height: 100px;" class="col m-1" onclick="playSound(clickingBuffer, 0, 1)">
Audio Context
</button>
</div>
<div class="row p-1 w-100">
<div class="col">
Press and hold:
</div>
<button id="autoNode" style="width: 100px; height: 100px;" class="col m-1" onmousedown="start('node')" onmouseup="stop()">
Auto Clone Node
</button>
<button id="autoContext" style="width: 100px; height: 100px;" class="col m-1" onmousedown="start('context')" onmouseup="stop()">
Auto Audio Context
</button>
</div>
</body>
</html>
Ok here is the code you want for your function. This code can use a local file to test with to rule out all kind of security issues (the xhr code is included). It uses plain JS ES5 and has been tested with firefox and chrome on different OS. Please put this into an audio_test.html as it is to verify the function. One word of warning, don't mix html tags and java script function calls, use event listeners as I demostrate it in the code.The stop button function is just a starter, to relock after play extra code is necessary I didn't bother to write.
Do not try to create buffers in an ongoing way because this fills up memory and crashes the browsers/OS. If you want overlapping sound this means using buffer arrays, but thats would be an other question.
<!DOCTYPE html>
<!-- Author: codebreaker007 # stackoverflow -->
<html class="h-100" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Web Audio API: load + play</title>
</head>
<body>
<p>Example of using the Web Audio API to load a sound file and </br>play once, play continous on mousedown or stop play
and start playing on user-click.</p>
Tested in Firefox and Chrome</p>
<input type="file" accept="audio/*" value="">
<button id="playonce" disabled=disabled>Play once</button>
<button id="playstop" disabled=disabled>Stop play</button>
<button id="playcont" disabled=disabled>Play cont</button>
<script>
/* global AudioContext:true,
*/
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
var source = null;
var clickingBuffer = null;
var mouseIsDown = false;
var buttonPo = document.getElementById("playonce");
var buttonPs = document.getElementById("playstop");
var buttonPc = document.getElementById("playcont");
if (document.readyState!="loading") docReady();
/* Modern browsers */
else document.addEventListener("DOMContentLoaded", docReady);
function docReady() {
buttonPo.addEventListener("click", function(e){
playSound(clickingBuffer, 0, 0, 0.8);
buttonPs.disabled = false;
});
buttonPs.addEventListener("click", function(e){
if (source) {
source.stop(0);
}
buttonPs.disabled = true;
});
buttonPc.addEventListener("mousedown", function(e){
playSound(clickingBuffer, 1, 0, 1);
// while(mouseIsDown) playSound(clickingBuffer, 0, 1);
});
buttonPc.addEventListener("mouseup", function(e){
if (source) {
source.stop(0);
}
});
}
function playSound(buffer2play, isLoop, time, volume) {
console.log("playsound called");
source = context.createBufferSource(); // creates a sound source
source.buffer = buffer2play; // tell the source which sound to play
if (isLoop) source.loop = true;
else source.loop = false;
source.connect(context.destination); // connect the source to the context's destination (the speakers)
var gainNode = context.createGain(); // Create a gain node
source.connect(gainNode); // Connect the source to the gain node
gainNode.connect(context.destination); // Connect the gain node to the destination
gainNode.gain.value = volume; // Set the volume
source.start(time); // play the source at the deisred time 0=now
console.log("playSound");
}
function initSound(arrayBuffer) {
context.decodeAudioData(arrayBuffer, function(buffer) {
// clickingBuffer is global to reuse the decoded audio later.
clickingBuffer = buffer;
// Test routine activate buttons
buttonPo.disabled = false;
buttonPc.disabled = false;
}, function(e) {
console.log('Error decoding file', e);
});
}
// User selects file, read it as an ArrayBuffer and pass to the API.
var fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', function(e) {
var reader = new FileReader();
reader.onload = function(e) {
initSound(this.result);
};
reader.readAsArrayBuffer(this.files[0]);
}, false);
// Load file from a URL as an ArrayBuffer.
// Example: loading via xhr2: loadSoundFile('sounds/test.mp3');
function loadClickSound(url) {
console.log("loading sound");
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
// Decode asynchronously
initSound(this.response); // this.response is an ArrayBuffer.
};
xhr.send();
}
</script>
</body>
</html>

Refresh a generated image

I am fairly unfamiliar with web technology.
A software that embeds a web server output a dynamic image
on the local host:
<img src="http://localhost:8000/" alt="http://localhost:8000/" class="transparent shrinkToFit" width="419" height="428">
This image is updated regularly by the software. I am trying to display this update in the web browser. There are several related posts and I have tried two solutions but so far with no luck.
Below are two attempts inspired by existing code and both fail. The problem seems to be related to some caching effect but I am not sure how to work around this.
Thanks in advance,
Trad
<html>
<head>
<title></title>
<meta content="">
<style></style>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="rsc/stylesheet.css" type="text/css" charset="utf-8" />
<!-- <script>
setInterval(function() {
var url = "http://localhost:8000";//document.getElementById("url").value;
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == xhr.DONE && xhr.status == 200 ) { // xhr.readyState == xhr.DONE &&
// Render the downloaded image
var myblob = xhr.response;
var image = document.getElementById("ImageMusic");
image.addEventListener("load", function (evt) {
URL.revokeObjectURL(evt.target.src);
});
image.src = URL.createObjectURL(myblob);
}
}
xhr.send(null);
}, 100);
</script>
-->
<script>
setInterval(function() {
var myImageElement = document.getElementById('ImageMusic');
myImageElement.src = 'http://localhost:8000?rand=' + Math.random();
}, 100);
</script>
<script src="https://aframe.io/releases/0.3.0/aframe.min.js"></script>
</head>
<body>
<a-scene>
<a-assets>
<img id="ImageMusic" src="http://localhost:8000" />
</a-assets>
<a-image position="1 1 -4" width="4" height="4" src="#ImageMusic"></a-image>
</a-scene>
</body>
</html>
It is not possible to use a web page as an image or texture.
In the context of A-Frame, you cannot use I-Frames as an image or texture either, it is not possible in the browser.
Try using iframe
<iframe src="http://localhost:8000/">Your browser does not support the iframe HTML tag</iframe>
This should update automatically.
Alternatively, you can use the <embed src="http://localhost:8000/"></embed> tag. As long as you have a set pixel size for the images, (eg: 1080x720), you shouldn't have any problems with scrolling or stretched images.
CSS:
embed {
width:1080px;
height: 720px;
}

Phonegap Camera API - Cannot read property 'DATA_URL' of undefined

I am creating an Android app using Phonegap.
I have installed phonegap using the commands on their website.
Everything is up and running with the SDK and Emulator.
Now when I run the example camera script from their website to get it working before I start cusotmising it.
Everytime I run the code below (even though I have the file linked to phonegap.js) it keeps throwing an error. I mean the script runs as far as the HTML and showing the buttons, but when the button is clicked nothing happens and in the log it says: Cannot read property 'DATA_URL' of undefined.
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="phonegap.js"></script>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<title>Retouch</title>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoFileSuccess(imageData) {
// Get image handle
console.log(JSON.stringify(imageData));
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
function capturePhotoEdit() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.Camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: pictureSource
});
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<!-- Navigation bar -->
<div class="fixed">
<nav class="top-bar fixed" data-topbar>
<ul class="title-area">
<li class="name">
<h1 class="navmsg">
<script>
var Digital=new Date()
var hours=Digital.getHours()
if (hours>=5&&hours<=11)
document.write('<b>Good Morning.</b>')
else if (hours==12)
document.write('<b>Good Afternoon.</b>')
else if (hours>=13&&hours<=17)
document.write('<b>Good Afternoon.</b>')
else if (hours>=18&&hours<=20)
document.write('<b>Good Evening.</b>')
else if (hours>=21&&hours<=11)
document.write('<b>Hello!</b>')
else
document.write('<b>Hello!</b>')
</script>
</h1>
</li>
<li class="toggle-topbar menu-icon">Account</li>
</ul>
</nav>
</div>
<button onclick="capturePhotoWithData();">Capture Photo With Image Data</button> <br>
<button onclick="capturePhotoWithFile();">Capture Photo With Image File URI</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>`
I have tried to use the following:
<script type="text/javascript" src="phonegap.js"></script>
and
<script type="text/javascript" src="cordova.js"></script>
Nothing seems to work.
I have changed the following in capturePhoto() and capturePhotoEdit() from:
destinationType.DATA_URL
to
Camera.DestinationType.DATA_URL
Still no luck with the functionality. I suspect it has something to do with the cordova plugin and phonegap, as I only have phonegap.js included in the script. I'm also reading about settings in the config.xml, which I have done through command line (unless I have done it wrong) following the docs.
I have built the application by CL:
phonegap build android
The following code with cordova-2.5.0.js and destinationType.FILE_URI added has successfully enabled the getPhoto() functions and allows me to display the photos in library/album.
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script type="text/javascript" src="phonegap.js"></script>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
<title>Retouch</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
//alert(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
alert("inside large image")
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail,
{ quality: 20, allowEdit: true,
destinationType: destinationType.FILE_URI });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<!-- Navigation bar -->
<div class="fixed">
<nav class="top-bar fixed" data-topbar>
<ul class="title-area">
<li class="name">
<h1 class="navmsg">
<script>
var Digital=new Date()
var hours=Digital.getHours()
if (hours>=5&&hours<=11)
document.write('<b>Good Morning.</b>')
else if (hours==12)
document.write('<b>Good Afternoon.</b>')
else if (hours>=13&&hours<=17)
document.write('<b>Good Afternoon.</b>')
else if (hours>=18&&hours<=20)
document.write('<b>Good Evening.</b>')
else if (hours>=21&&hours<=11)
document.write('<b>Hello!</b>')
else
document.write('<b>Hello!</b>')
</script>
</h1>
</li>
<li class="toggle-topbar menu-icon">Account</li>
</ul>
</nav>
</div>
<button onclick="capturePhotoWithData();">Capture Photo With Image Data</button> <br>
<button onclick="capturePhotoWithFile();">Capture Photo With Image File URI</button> <br>
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
I tried adding 'destinationType.FILE_URI' to capturePhoto() and capturePhotoEdit() functions, but they still don't seem to work.
I have now tried the following three types:
destinationType.FILE_URI
destinationType.DATA_URI
Camera.desitnationType.DATA_URI
None of them seem to make a difference.
That is a Javascript error. You are trying to access a property of an undefined variable. This line (in the capturePhoto and capturePhotoEdit methods):
destinationType.DATA_URL
should be:
Camera.DestinationType.DATA_URL
One more thing: With Cordova it is always good to have the docs at hand, and have a look at them each time you are using a new plugin, or when you upgrade to a newer version (they tend to change the API frequently, hence the examples found in Google usually show legacy code). Here you have the Camera plugin documentation.
In my case when I pause the execution Camera has getPicture() method but not DestinationType and PictureSourceType propreties.
$scope.tomarFoto = function(){
$ionicPlatform.ready(function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.CAMERA
};
$cordovaCamera.getPicture(options).then(function (imageData) {
$scope.cameraimage = "data:image/jpeg;base64," + imageData;
}, function (err) {
console.log('Failed because: ' + message);
});
});
UPDATED
Just I got recently the same problem.
If did you add the camera plugin and all the permissions needed, mainly you did all the Phonegap Api steps. I think you'r solution pass for go to you'r project folder and execute phonegap build or phonegap build app_platform.
First save you'r project data cause that command line reset the estructure of the project and delete the files you add.
Make me know if that works for you too, good luck.

jQuery/Javascript: Button - replaces images

I have little knowledge of JavaScript and need some help. I have this code (below) which when the countdown finishes, it replaces the image with a new one.
I wanted to modify this so that instead of a countdown - a button (img) is pressed instead. Here's my design to get an idea: Design.
I'm guessing I'll need 4 imageloaders instead of just one this time (one for each box) and some code to make it so that when the "older ->" button is clicked it triggers the loading of images?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript" charset="UTF-8"></script>
<script src="js/jquery.countdown.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
<!-- The ready() function will force the browser to run wait running the javascript until the entire page has loaded -->
$(document).ready(function() {
// The jquery code for constructing and starting the counter
// has been wrapped inside a function so we can call it whenever we want to
function startCounter(imageLoader){
$('#counter_2').countdown({
image: 'img/digits.png',
startTime: '00:03',
timerEnd: function(){ callback(imageLoader) },
format: 'mm:ss'
})
}
// Takes care of whatever need to be done every time
function callback(imageLoader){
// Replace image
$('#image').attr('src', imageLoader.nextImage());
// Clear the finished counter, so a new can be constructed in its place
$('#counter_2').empty();
// Construct a new counter and starts it
startCounter(imageLoader);
}
function ImageLoader(images){
this.images = images;
this.current = 0;
this.nextImage = function(){
this.current = (this.current+1) % this.images.length;
return this.images[this.current];;
}
}
// Fill in images in this array
imageLoader = new ImageLoader(['img/turd.png', 'img/guitar.gif', 'img/carrot.jpg', 'img/puppy.jpg']);
// Set everything off! (Construct a new counter and starts it)
startCounter(imageLoader);
});
</script>
<style type="text/css">
div.counter{
font-size: 36px;
font-weight: bold;
line-height: 77px;
}
</style>
</head>
<body>
<div id="counter_2" class="counter"></div>
<img id="image" src="img/turd.png" alt="Hot steaming turd">
</body>
</html>
Thanks everyone, I'm really stuck and really appreciate your help.

Categories

Resources