accessing webcam in web pages - html

I am developing a web application.
In my guest registration page I need to access web cam for taking images of guests.
The image which I take could be able to stored in a specified location.
Which will be the best way to perform this.
Methods using java, JSP, html, java script or any other methods are welcomed.

Answering own question, as there is a better way using HTML5 is available.
Option 1, Accessing default camera from the system
HTML
Video Tag
<br/>
<div class="camera">
<video id="video">Video stream not available.</video>
<button id="startbutton">Take photo</button>
</div>
<br/>
Canvas
<br/>
<canvas id="canvas"></canvas>
Script
var width = 320;
var height = 0;
var streaming = false;
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function (stream) {
video.srcObject = stream;
video.play();
})
.catch(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);
startbutton.addEventListener('click', function (ev) {
takepicture();
ev.preventDefault();
}, false);
clearphoto();
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/jpeg", 0.95);
if (dataURL && dataURL != "data:,") {
var fileName = generateImageName();
uploadimage(dataURL, fileName);
} else {
alert("Image not available");
}
} else {
clearphoto();
}
}
function generateImageName() {
... generate image name logic here ...
return imageName;
}
function uploadimage(dataurl, filename) {
... upload logic here ...
}
Screen shot
Option 2, Provide a list of available cameras in the system, and let user select the camera.
HTML
<select id="videoSelect"></select>
<button id="startCameraButton">Start Camera</button>
<br/>
Video Tag
<br/>
<div class="camera">
<video id="video">Video stream not available.</video>
<button id="takePictureButton">Take photo</button>
</div>
<br/>
Canvas
<br/>
<canvas id="canvas">
</canvas>
Script
var width = 320;
var height = 0;
var streaming = false;
var localstream = null;
startCameraButton.onclick = start;
takePictureButton.onclick = takepicture;
navigator.mediaDevices.enumerateDevices()
.then(gotDevices)
.catch(function (err) {
console.log("An error occured while getting device list! " + err);
});
function gotDevices(deviceInfos) {
while (videoSelect.firstChild) {
videoSelect.removeChild(videoSelect.firstChild);
}
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
}
}
}
function start() {
stopVideo();
clearphoto();
var videoSource = videoSelect.value;
var constraints = {
audio: false,
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError);
}
function gotStream(stream) {
localstream = stream;
video.srcObject = stream;
video.play();
// Refresh button list in case labels have become available
return navigator.mediaDevices.enumerateDevices();
}
function handleError(error) {
console.log('navigator.getUserMedia error: ', error);
}
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);
clearphoto();
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var dataURL = canvas.toDataURL("image/jpeg", 0.95);
if (dataURL && dataURL != "data:,") {
var fileName = generateImageName();
fileName = fileName + ".txt"
uploadimage(dataURL, fileName);
} else {
console.log("Image not available");
}
} else {
clearphoto();
}
}
function generateImageName() {
... generate image name logic here ...
return imageName;
}
function uploadimage(dataurl, filename) {
... upload logic here ...
}
function stopVideo() {
if (localstream) {
localstream.getTracks().forEach(function (track) {
track.stop();
localstream = null;
});
}
}
Screen Shot
Option 3, let user select audio and video sources and audio output
In option 2, user can select any particular camera. On top of that if user want to select audio source and audio output source also, modify the above code with below changes.
HTML
audioInputSelect
<br/>
<select id="audioInputSelect"></select>
<br/>
audioOutputSelect
<select id="audioOutputSelect"></select>
Script
function gotDevices(deviceInfos) {
while (videoSelect.firstChild) {
videoSelect.removeChild(videoSelect.firstChild);
}
for (var i = 0; i !== deviceInfos.length; ++i) {
var deviceInfo = deviceInfos[i];
var option = document.createElement('option');
option.value = deviceInfo.deviceId;
if (deviceInfo.kind === 'audioinput') {
option.text = deviceInfo.label || 'Microphone ' + (audioInputSelect.length + 1);
audioInputSelect.appendChild(option);
} else if (deviceInfo.kind === 'audiooutput') {
option.text = deviceInfo.label || 'Speaker ' + (audioOutputSelect.length + 1);
audioOutputSelect.appendChild(option);
} else if (deviceInfo.kind === 'videoinput') {
option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
videoSelect.appendChild(option);
}
}
}
function start() {
stopVideo();
clearphoto();
var audioSource = audioInputSelect.value;
var videoSource = videoSelect.value;
var constraints = {
audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
video: {deviceId: videoSource ? {exact: videoSource} : undefined}
};
navigator.mediaDevices.getUserMedia(constraints).
then(gotStream).then(gotDevices).catch(handleError);
}

jQuery Webcam Plugin does the hard work for you:
http://www.xarg.org/project/jquery-webcam-plugin/

Related

fabricJS: Scale canvas view

I have converted a pdf to image format using PDF.JS and rendered that to the canvas. While that process the rendered pdf image is showing blurred in the canvas.
I have no idea how to scale the image to some viewable format rather than being so blurred.
Image of the pdf in canvas:
Here in the image you can clearly see that the rendered image is not in readable format!
Here is the fiddle link: https://jsfiddle.net/kjxes63f/
var fabricCanvas;
fabricCanvas = new fabric.Canvas('firtcanvas');
document.querySelector("#pdf-upload").addEventListener("change", function (e) {
var file = e.target.files[0]
console.log("pdf evente");
console.log(e);
if (file.type != "application/pdf") {
console.error(file.name, "is not a pdf file.")
return
}
var fileReader = new FileReader();
fileReader.onload = function () {
var typedarray = new Uint8Array(this.result);
console.log("typedarray");
console.log(typedarray);
console.log("this.result");
console.log(this.result);
PDFJS.getDocument(typedarray).then(function (pdf) {
// you can now use *pdf* here
console.log("the pdf has ", pdf.numPages, "page(s).")
pdf.getPage(pdf.numPages).then(function (page) {
// you can now use *page* here
var viewport = page.getViewport(2.0);
var fabricCanvas = document.querySelector("#firtcanvas")
fabricCanvas.height = viewport.height;
fabricCanvas.width = viewport.width;
page.render({
canvasContext: fabricCanvas.getContext('2d'),
viewport: viewport
}).then(function () {
bg = fabricCanvas.toDataURL("image/png");
fabric.Image.fromURL(bg, function (img) {
img.scaleToHeight(800);
img.scaleToWidth(600);
console.log("img");
console.log(img);
console.log(bg);
var imgCanvas = img.set({ left: 0, top: 0, width: 150, height: 150 });
fabricCanvas.add(imgCanvas);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
});
Construction drawings are often wide-format and hard to read onscreen without zoom. As a work-around I'd suggest adding a zoom function to your canvas like below.
var canvas = new fabric.Canvas('pdfcanvas');
canvas.selection = false;
canvas.setHeight(450);
canvas.setWidth(636);
//zoom function
canvas.on('mouse:wheel', function(opt) {
var delta = opt.e.deltaY;
var pointer = canvas.getPointer(opt.e);
var zoom = canvas.getZoom();
zoom = zoom - delta / 200;
if (zoom > 10) zoom = 10;
if (zoom < 1) {
zoom = 1;
canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
}
canvas.zoomToPoint({
'x': opt.e.offsetX,
'y': opt.e.offsetY
}, zoom);
opt.e.preventDefault();
opt.e.stopPropagation();
});
//pdf load
document.querySelector('#pdf-upload').addEventListener('change', function(e) {
var pageEl = document.getElementById('page-container');
var file = e.target.files[0];
if (file.type == 'application/pdf') {
var fileReader = new FileReader();
fileReader.onload = function() {
var typedarray = new Uint8Array(this.result);
PDFJS.getDocument(typedarray).then(function(pdf) {
//console.log('the pdf has ', pdf.numPages, 'page(s).');
pdf.getPage(pdf.numPages).then(function(pageEl) {
var viewport = pageEl.getViewport(2.0);
var canvasEl = document.querySelector('canvas');
canvasEl.height = viewport.height;
canvasEl.width = viewport.width;
pageEl.render({
'canvasContext': canvasEl.getContext('2d'),
'viewport': viewport
}).then(function() {
var bg = canvasEl.toDataURL('image/png');
fabric.Image.fromURL(bg, function(img) {
canvas.setBackgroundImage(img);
});
});
});
});
};
fileReader.readAsArrayBuffer(file);
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
<input id="pdf-upload" type="file">
<div id="page-container">
<canvas id="pdfcanvas"></canvas>
</div>

Fabric.js canvas image disappear after loading image second time

Hello i am uploading a image once image will upload ,i am loading that image in canvas which i am creating in popup.
Once image is loaded it appears in pop up where i am performing crop functionality,everything is working fine but when i am uploading image second time
image appears but when i click on image to crop it image disappears on canvas.
Please suggest me how to fix the issue?
Here is my code
handleImage1= function(e) {
var mousex = 0;
var mousey = 0;
var reader = new FileReader();
var baseUrl = jQuery("#base-url").val();
var file = this.files[0];
var fd = new FormData();
fd.append("afile", file);
var mouseDown;
// only allow one crop. turn it off after that
var disabled = false;
var rect;
var container = document.getElementById('c1').getBoundingClientRect();
var canvas1 = new fabric.Canvas('c1');
var center = canvas1.getCenter();
//canvas1.add(rect);
var image;
var isDown, origX, origY;
var rawImageid;
var result='';
var object;
jQuery.ajax({
type : 'POST',
url : baseUrl+'personalized/index/saveRawImage',
data : fd,
dataType : 'text',
cache: false,
beforeSend: function(){
jQuery('#divLoading').show();
},
contentType: false,
processData: false,
success : function(result) {
result=result;
var imgSizeObj;
fabric.util.loadImage(result, function(img) {
image = new fabric.Image(img);
image.selectable = false;
image.originX= 'center',
image.originY= 'center',
//image.top=center.top,
//image.left=center.left,
imgSizeObj = image.getOriginalSize();
width_ratio = canvas1.width / image.width;
height_ratio = canvas1.height / image.height;
if (height_ratio>width_ratio ) {
fw = image.width * width_ratio;
fh = image.height*fw/image.width;
} else {
fh = image.height * height_ratio;
fw = image.width*fh/image.height;
}
if (imgSizeObj.width > canvas1.width || imgSizeObj.height > canvas1.height) {
image.set({
width: fw,
height: fh
});
}
canvas1.add(image);
canvas1.centerObject(image);
canvas1.renderAll();
});
// capture the event when the user clicks the mouse button down
canvas1.on('mouse:down', function(o){
isDown = true;
var pointer = canvas1.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var pointer = canvas1.getPointer(o.e);
canvas1.remove(rect);
rect = new fabric.Rect({
left: origX,
top: origY,
originX: 'left',
originY: 'top',
width: pointer.x-origX,
height: pointer.y-origY,
angle: 0,
opacity:0.5,
transparentCorners: false,
hasControls: false,
hasBorders: false
});
canvas1.add(rect);
canvas1.renderAll()
});
// draw the rectangle as the mouse is moved after a down click
canvas1.on('mouse:move', function(o){
if (!isDown) return;
var pointer = canvas1.getPointer(o.e);
if(origX>pointer.x){
rect.set({ left: Math.abs(pointer.x) });
}
if(origY>pointer.y){
rect.set({ top: Math.abs(pointer.y) });
}
rect.set({ width: Math.abs(origX - pointer.x) });
rect.set({ height: Math.abs(origY - pointer.y) });
canvas1.renderAll();
});
canvas1.on('mouse:up', function(o){
isDown = false;
});
jQuery('#cropB').on('click', function() {
image.selectable = true;
disabled = true;
rect.visible = false;
var cropped = new Image();
cropped.src = canvas1.toDataURL({
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height
});
fabric.util.loadImage(cropped.src, function(img) {
var image1 = new fabric.Image(img);
image1.selectable = true;
canvas.add(image1);
canvas.centerObject(image1);
image1.selectable = true;
canvas.renderAll();
});
canvas1.clear();
jQuery('#changePic').modal('hide');
});
jQuery('#add_image_custom').on('click',function(){
var rawImageValue = jQuery("#rawImages").val();
rawImageid = result;
if(rawImageValue == 0){
rawImageValue = result;
}else{
rawImageValue = rawImageValue + ','+ result;
}
jQuery("#rawImages").val(rawImageValue);
var img = new Image();
var center = canvas.getCenter();
img.onload = function () {
var imgInstance = new fabric.Image(img, {
originX: 'center',
originY: 'center',
top: center.top,
left: center.left,
});
var imgSizeObj = imgInstance.getOriginalSize();
//alert(imgSizeObj.width+'|'+imgSizeObj.height+'|'+canvas.width+'|'+canvas.height);
width_ratio = canvas.width / imgSizeObj.width;
height_ratio = canvas.height / imgSizeObj.height;
if (height_ratio>width_ratio ) {
fw = imgSizeObj.width * width_ratio;
fh = imgSizeObj.height*fw/imgSizeObj.width;
} else {
fh = imgSizeObj.height * height_ratio;
fw = imgSizeObj.width*fh/imgSizeObj.height;
}
if (imgSizeObj.width > canvas.width || imgSizeObj.height > canvas.height) {
imgInstance.set({
width: fw,
height: fh
});
}
if(canvas.width<400)
{
imgInstance.scaleX = canvas.width*0.9/imgInstance.width;
imgInstance.scaleY = imgInstance.scaleX;
}
imgInstance.RawImageId=rawImageid;
canvas.add(imgInstance);
}
img.src = result;
reader.readAsDataURL(e.target.files[0]);
canvas1.clear();
jQuery('#changePic').modal('hide');
});
/*Shrink fit code end here---------------------------------*/
//imgpopup.src = src1;
//canvas1.add(image);
//canvas1.renderAll();
//jQuery('#main-image').attr('src',result);
//jQuery('#main-image').show();
setTimeout(function(){
jQuery('#changePic').modal();
jQuery('#divLoading').hide();
}, 300);
},
error : function(xhr, status) {
//console.log(status);
//console.log(xhr); //
jQuery('.loading').hide();
}
});
}

broken image after writing Base64 image using FileWriter

I want to add some text over image taken from device camera using cordova camera plugin.
For that i used canvas and draw text over the image and saved using FileWriter.writer() method, but while i checked image in gallery, image is shown as broken and, in proprties resolution is -1x-1.
while i debug, before calling write() i am able see base64 image and when i clicked,image is opened in new tab.
Please find my code and please provide your comments.
var gImageURI = '';
var gFileSystem = {};
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, errorHandler);
function getPhoto(source, type) {
navigator.camera.getPicture(function (imageURI) { onPhotoURISuccess(imageURI, type) }, onFail, {
quality: 35,
destinationType: navigator.camera.DestinationType.FILE_URI,
saveToPhotoAlbum: false,
sourceType: source,
allowEdit: false,
targetWidth: 600,
targetHeight: 800
});
}
// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI, type) {
if(type=="camera")
canvasimage(imageURI);
}
// Called if something bad happens.
function onFail(message) {
console.log('Failed because: ' + message);
}
// sets the filesystem to the global var gFileSystem
function gotFS(fileSystem) {
gFileSystem = fileSystem;
}
// send the full URI of the moved image to the updateImageSrc() method which does some DOM manipulation
function movedImageSuccess(fileEntry, type) {
debugger;
updateImageSrc(fileEntry.fullPath, type);
}
// simple error handler
function errorHandler(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = e.code;
break;
};
console.log('Error: ' + msg);
}
function btnCameraClick() {
$("#divAttachments").show();
$("#divLandmarks").hide();
getPhoto(navigator.camera.PictureSourceType.CAMERA, 'camera');
}
function updateImageSrc(filepath, type) {
try {
var filenamewithextensn = filepath.substring(filepath.lastIndexOf('/') + 1);
var strfilename = filenamewithextensn.split('.');
var filename = strfilename[0];
var tag = filepath.substring(filepath.lastIndexOf('/') + 1);
// alert('File Path after moving : ' + filepath);
// alert('tag :' + tag);
var fullpath = gFileSystem.root.toURL() + tag;
// alert('full path to dataabase '+fullpath);
var query = "";
if (type == "camera") {
//query= insert query
}
}
catch (err) {
ErrorMessageDB("something");
}
}
function canvasimage(src) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var imgdata = new Image;
imgdata.onload = function () {
canvas.width = this.width;
canvas.height = this.height;
ctx.drawImage(this, 0, 0);
ctx.font = "11pt Verdana";
ctx.fillStyle = "black";
ctx.fillText("19-11-2014", 22, 42);
ctx.fillStyle = "white";
ctx.fillText("19-11-2014", 20, 40);
var dataURL = canvas.toDataURL();
//alert(dataURL);
//dataURL=dataURL.substring(dataURL.indexOf("base64\,") + 7);
gotfilesystem(dataURL);
}
imgdata.src = src;
//var index = dataURL.indexOf(',');
//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
// return dataURL;
}
function gotfilesystem(dataURL) {
var d = new Date();
var s = d.getDate().toString() + d.getMonth().toString() + d.getMinutes().toString() + d.getSeconds().toString()
var fname="thumbnail_" + s + ".png";
gFileSystem.root.getFile(fname, { create: true, exclusive: false },
function(entry) {
gotfileentrysuccess(entry, dataURL);
}, function() {
});
}
function gotfileentrysuccess(entry, dataURL) {
entry.createWriter( function(fileWriter) {gotFileWriter(fileWriter,dataURL,entry)});
}
function gotFileWriter(writer, dataURL,entry) {
writer.onwriteend = function(evt) {
movedImageSuccess(entry, 'camera');
};
writer.write(dataURL);
}
You need to create a Blob using your base64 string then pass the Blob to the FileWriter.writer() method.
There is a nice example of how to do this here:
Convert Data URI to File then append to FormData

jquery webcam not working in chrome 35

I am trying to access webcam from jquery webcam API. The sample given below works fine in IE9, Firefox, but unfortunately does not work in Chrome v35. It shows the webcam activated but when I click the "Take Picture" button, it gives me a javascript error saying that webcam.capture is undefined. In the code below, the webcam object does not have any function called capture() in chrome; but its found for Firefox and IE9.
Please help me out!!
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.11.0.js"></script>
<script type="text/javascript" src="jquery.webcam.min.js"></script>
</head>
<body>
<p id="status" style="height:22px; color:#c00;font-weight:bold;"></p>
<div id="webcam" style="width:350px;float: left;"">
Take a picture instantly
</div>
<p style="width:350px; float: left;"><canvas id="canvas" height="240" width="320" style="float: left;""></canvas></p>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
main.js
var pos = 0;
var ctx = null;
var cam = null;
var image = null;
var filter_on = false;
var filter_id = 0;
function changeFilter() {
if (filter_on) {
filter_id = (filter_id + 1) & 7;
}
}
function toggleFilter(obj) {
if (filter_on =!filter_on) {
obj.parentNode.style.borderColor = "#c00";
} else {
obj.parentNode.style.borderColor = "#333";
}
}
jQuery("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "http://www.xarg.org/download/jscam_canvas_only.swf",
onTick: function(remain) {
if (0 == remain) {
jQuery("#status").text("Cheese!");
} else {
jQuery("#status").text(remain + " seconds remaining...");
}
},
onSave: function(data) {
var col = data.split(";");
var img = image;
for(var i = 0; i < 320; i++) {
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 0x4B000) {
ctx.putImageData(img, 0, 0);
pos = 0;
}
},
onCapture: function () {
webcam.save();
jQuery("#flash").css("display", "block");
jQuery("#flash").fadeOut(100, function () {
jQuery("#flash").css("opacity", 1);
});
},
debug: function (type, string) {
jQuery("#status").html(type + ": " + string);
},
onLoad: function () {
var cams = webcam.getCameraList();
for(var i in cams) {
jQuery("#cams").append("<li>" + cams[i] + "</li>");
}
}
});
function getPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
return [pageWidth, pageHeight];
}
window.addEventListener("load", function() {
jQuery("body").append("<div id=\"flash\"></div>");
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
ctx = document.getElementById("canvas").getContext("2d");
ctx.clearRect(0, 0, 320, 240);
var img = new Image();
img.src = "logo.gif";
img.onload = function() {
ctx.drawImage(img, 129, 89);
}
image = ctx.getImageData(0, 0, 320, 240);
}
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
window.addEventListener("resize", function() {
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
I think I found the answer. I was initially trying to run the code from a folder location on my system. But when I deployed the same code to a local web application running on tomcat (http://<>/webcam/webcam.html), it started working in chrome!! I was anyhow going to deploy the code tomorrow on a remote server but had no idea that the webcam APIs would be inaccessible from the system if the application is not running on a server. Quite strange, but this saved me!!

sending canvas content to server in PNG or JPEG format

I have this code which on executing embed flash in page and on clicking it captures flash bitmap into canvas..here upto works fine but problem is how to send that capture data into canvas to server into PNG or JPEG image format.
I used Jquery webcam plugin and jquery.js to load flash
<html>
<body>
<br><br>
<form name="f" id="f" runat="server"><table><tr><!--<td><div id="eflash">
</div></td>-->
<td>
<div id="webcam">
</div></td><td><canvas style="border:2px solid red" id="canvas" width="320" height="240">
</canvas>
</td></tr></table>
<br><p>CLICK**|**<input type="button" id="sendBtn" value="Send" /></p>
</form>
</body></html>
<script type="text/javascript" src="./jquery/jquery.js"></script>
<!--<script type="text/javascript" src="./jquery/jquery.flash.js"></script>-->
<script type="text/javascript" src="./jquery/jquery.webcam.js"></script>
<!--<script>
$(document).ready(
function() {
$('#eflash').flash({src: 'jscam.swf', width: 220, height: 140 });
}
);
</script>-->
<script type="text/javascript">
var pos = 0;
var ctx = null;
var cam = null;
var image = null;
jQuery("#webcam").webcam({
width: 320,
height: 240,
mode: "callback",
swffile: "jscam_canvas_only.swf",
onTick: function(remain) {
if (0 == remain)
{jQuery("#status").text("Sorria!");
}
else {
jQuery("#status").text(remain + " segundo(s) restante(s)...");
}
},
onSave: function(data)
{
var col = data.split(";");
var img = image;
for(var i = 0; i < 320; i++)
{
var tmp = parseInt(col[i]);
img.data[pos + 0] = (tmp >> 16) & 0xff;
img.data[pos + 1] = (tmp >> 8) & 0xff;
img.data[pos + 2] = tmp & 0xff;
img.data[pos + 3] = 0xff;
pos+= 4;
}
if (pos >= 4 * 320 * 240)
{
ctx.putImageData(img, 0, 0);
var canvas = document.getElementById("canvas");
var save_image = canvas.toDataURL("image/jpeg");
save_image = save_image.replace(/^data:image\/(png|jpeg);base64,/, "");
$('input[name=save_image]').val(save_image);
pos = 0;
}
},
onCapture: function ()
{
jQuery("#flash").css("display", "block");
jQuery("#flash").fadeOut(100, function () {jQuery("#flash").css("opacity", 1);});
jQuery("#canvas").show();
webcam.save();
},
onLoad: function ()
{ var cams = webcam.getCameraList();
for(var i in cams) {jQuery("#cams").append("<li>" + cams[i] + "</li>");}
jQuery("#canvas").hide();}
});
function getPageSize()
{
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY)
{
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
}
else
if (document.body.scrollHeight > document.body.offsetHeight)
{ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
}
else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight)
{ // all except Explorer
if(document.documentElement.clientWidth)
{
windowWidth = document.documentElement.clientWidth;
}
else
{
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
}
else
if (document.documentElement && document.documentElement.clientHeight)
{ // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
}
else
if (document.body)
{ // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight)
{
pageHeight = windowHeight;
}
else
{
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth)
{
pageWidth = xScroll;
}
else
{
pageWidth = windowWidth;
}
return [pageWidth, pageHeight]; }
window.addEventListener("load", function()
{
jQuery("body").append("<div id=\"flash\"></div>");
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
ctx = document.getElementById("canvas").getContext("2d");
ctx.clearRect(0, 0, 320, 240);
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 320, 240);
}
image = ctx.getImageData(0, 0, 320, 240);
}
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
window.addEventListener("resize", function() {
var pageSize = getPageSize();
jQuery("#flash").css({ height: pageSize[1] + "px" });
}, false);
</script>