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

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.

Related

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

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>

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;
}

PIXI.js render not working

I'm following this tutorial (http://www.yeahbutisitflash.com/?p=5226), using Chrome, and can't figure out why this isn't working. Here is my console output:
init() successfully called.
pixi.dev.js:224 Pixi.js v2.2.7 - webGL http://www.pixijs.com/ ♥♥♥
index2.html:26 PIXI.WebGLRenderer
index2.html:28 render complete.
And here is my code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Endless Runner Game Demo</title>
</head>
<body onload="init();">
<div align="center">
<canvas id="game-canvas" width="512" height="384"></canvas>
</div>
<script src="js/pixi.js-master/bin/pixi.dev.js"></script>
<script>
function init() {
console.log("init() successfully called.");
stage = new PIXI.Stage(0x66FF99);
renderer = PIXI.autoDetectRenderer(
512,
384,
document.getElementById("game-canvas")
);
console.log(renderer);
renderer.render(stage);
console.log("render complete.");
}
</script>
</body>
</html>
Yet, it displays nothing. The tutorial says I should see the background color set on the stage at this point.
Thanks.
The third argument of PIXI.autoDetectRenderer should be an Object, not an element. You should set the Object property "view" to be your canvas element.
var renderer = PIXI.autoDetectRenderer( 512, 384, {
view: document.getElementById("game-canvas")
});
Also note that you may need to run a local server in order to view it in Chrome.

Api phonegap 3.3.0 camera for IOS not working

I'm developing an app that will capture and save a photo library on ipad, I am using the api library will phonegap camera, and I'm having trouble because the code is not returning any errors so I can know what is happening can someone help me This is my code
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
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
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line 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) {
// 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 in-line 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.DATA_URL });
}
// 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.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: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<button onclick="capturePhotoEdit();">Capture Editable Photo</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="" />
</body>
</html>
You have to explicitly add plugin via terminal (command line terminal) then your mention code will be working.
$ phonegap local plugin add org.apache.cordova.camera
$ phonegap local plugin add org.apache.cordova.media-capture
have you done this?

Canvas images do not load until click event... I want to load when page loads, how?

I am creating Battleships, the board game on an HTML5 canvas. I have a problem loading my ship images when the page is loaded. For some reason, the ship images only show when I click somewhere on the screen.
background info:
1.I have 2 canvas elements, each with 2 contexts
2.If I put the PlayerGrid.js before the OpponentGrid.js I have to click on the screen to get my ships to show up.
3.The Draw() is what draws the grid, and the images once they are created from the createShips(). createships() simply creates different ship objects and assigns images to each object.
4.I DO TRY CALLING DRAW() in many places, the onload, and the createShips(), but they still do not show.
Does anybody know what it could be? Is it a conflict in the context or canvases? The ship images DO show when I put the OpponentGrid.js BEFORE my PlayerGrid.js, but then there is a huge problem with my XMLHttpRequest that isn't worth solving.
How else should I call my Draw method after everything is loaded? Should I call my Draw() in my Battleship.html at the end somewhere?
Here's how to be sure all your images are loaded before you use them
Code and a Fiddle: http://jsfiddle.net/m1erickson/nD5jr/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var imageURLs=[];
var imagesOK=0;
var imagesFailed=0;
var imgs=[];
imageURLs.push("http://upload.wikimedia.org/wikipedia/commons/d/d4/New_York_City_at_night_HDR_edit1.jpg");
imageURLs.push("http://www.freebestwallpapers.info/bulkupload//20082010//Places/future-city.jpg");
loadAllImages();
function loadAllImages(){
for (var i = 0; i < imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = onLoad;
img.onerror = onFail;
img.src = imageURLs[i];
}
}
var imagesAllLoaded = function() {
if (imagesOK+imagesFailed==imageURLs.length ) {
// ALL IMAGES ARE NOW PROCESSED
// ready to use loaded images
// ready to handle failed image loads
ctx1.drawImage(imgs[0],0,0,canvas1.width,canvas1.height);
ctx2.drawImage(imgs[1],0,0,canvas2.width,canvas2.height);
}
};
function onLoad() {
imagesOK++;
imagesAllLoaded();
}
function onFail() {
// possibly log which images failed to load
imagesFailed++;
imagesAllLoaded();
};
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas1" width=300 height=300></canvas><br/>
<canvas id="canvas2" width=300 height=300></canvas>
</body>
</html>

Categories

Resources