sending canvas content to server in PNG or JPEG format - html

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>

Related

d3 svg transition has slight unwanted horizontal movement on Firefox

The following has some SVG squares that march upwards once per second. In Google Chrome it looks fine. In Firefox, the squares shift right and left by about 1 pixel which is not what I intended.
Can anyone help figure out why?
I'm sorry this code snippet is not simpler; this is about as basic as I could go from a much longer file in which I removed all the unrelated aspects.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<style type='text/css'>
.hidden {
display: none;
}
#ticktock {
position: absolute;
top: 550px;
left: 400px;
}
svg rect.cell {
fill: none;
stroke: steelblue;
}
</style>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(event) {
var L = 25;
var maxFacetCount = 8;
var state = {
nexttick: 0,
ticksize: 500,
n: -8,
nx: 8,
wheel: [],
nfacet: maxFacetCount,
init: true,
ticktock: true
};
function update_state(state)
{
if (state.ticktock)
{
if (state.wheel.length >= state.nfacet)
state.wheel.shift();
state.wheel.push({n: ++state.n });
}
}
state.wheel = state.wheel.slice(-1);
function prepare_view(state)
{
var width = 60 + (state.nx+0.5)*(L+2);
var height = 5 + (state.nfacet+0.5)*L;
var svg = d3.select("#wheel-container").append("svg")
.attr("width", width)
.attr("height", height);
var x1 = L*0.5+5;
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
}
prepare_view(state);
function facet_enter(facets, t)
{
var facet = facets.append('g');
for (var i = 0; i < state.nx; ++i)
{
facet.append('rect')
.attr('x',i*L)
.attr('y',0)
.attr('width',L)
.attr('height',L)
.attr('class','cell');
}
facet_move(facet, state.init ? null : t);
}
function facet_move(facet, t)
{
(t ? facet.transition(t) : facet)
.attr('opacity',function(d,i) {
var age = state.n - d.n;
return age == 0 ? 0 : 1-age/state.nfacet; })
.attr('transform',function(d,i) { return 'translate(0,'+((d.n-state.n+state.nfacet-1)*L)+')'; });
}
function facet_update(facets, t)
{
facet_move(facets, t);
}
function update_view(state, ticktock)
{
var wheel = d3.select("#wheel");
var facets = wheel.selectAll('g');
if (state.ticktock)
{
var t = d3.transition().duration(300);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd .call(facet_update, t)
.enter()
.call(facet_enter, t)
upd.exit()
.transition(t)
.attr('transform','translate (0,'+(-L)+')')
.remove();
}
else
{
// tock
var t = d3.transition().duration(100);
var t2 = t.transition().duration(100);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd.call(facet_update, t)
.enter()
.call(facet_enter, t);
}
}
var tmr = d3.timer(function(elapsed) {
var do_something = false;
while (elapsed >= state.nexttick)
{
do_something = true;
state.nexttick += state.ticksize;
}
if (do_something && !(d3.select('#pause').property('checked') ))
{
state.ticktock = !state.ticktock;
update_state(state);
update_view(state);
state.init = false;
}
} );
});
</script>
</head>
<body>
<div id='wheel-container' ></div>
<form class="">
<input type="checkbox" id="pause" name="pause">pause</input>
</form>
<div id='ticktock' class='hidden'></div>
</body>
</html>
Looks like floating-point rounding errors strike again. I changed to shape-rendering: crispEdges; and then rounded to an integer translate in one of the root elements and that seems to fix most of it (still a little residual y-axis shift).
was:
var x1 = L*0.5+5;
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
changed to:
var x1 = Math.round(L*0.5+5);
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<style type='text/css'>
.hidden {
display: none;
}
#ticktock {
position: absolute;
top: 550px;
left: 400px;
}
svg rect.cell {
fill: none;
stroke: steelblue;
shape-rendering: crispEdges;
}
</style>
<script type='text/javascript'>
document.addEventListener('DOMContentLoaded',function(event) {
var L = 25;
var maxFacetCount = 8;
var state = {
nexttick: 0,
ticksize: 500,
n: -8,
nx: 8,
wheel: [],
nfacet: maxFacetCount,
init: true,
ticktock: true
};
function update_state(state)
{
if (state.ticktock)
{
if (state.wheel.length >= state.nfacet)
state.wheel.shift();
state.wheel.push({n: ++state.n });
}
}
state.wheel = state.wheel.slice(-1);
function prepare_view(state)
{
var width = 60 + (state.nx+0.5)*(L+2);
var height = 5 + (state.nfacet+0.5)*L;
var svg = d3.select("#wheel-container").append("svg")
.attr("width", width)
.attr("height", height);
var x1 = Math.round(L*0.5+5);
var wheel = svg.append('g')
.attr('id','wheel')
.attr('transform','translate('+x1+',0)');
}
prepare_view(state);
function facet_enter(facets, t)
{
var facet = facets.append('g');
for (var i = 0; i < state.nx; ++i)
{
facet.append('rect')
.attr('x',i*L)
.attr('y',0)
.attr('width',L)
.attr('height',L)
.attr('class','cell');
}
facet_move(facet, state.init ? null : t);
}
function facet_move(facet, t)
{
(t ? facet.transition(t) : facet)
.attr('opacity',function(d,i) {
var age = state.n - d.n;
return age == 0 ? 0 : 1-age/state.nfacet; })
.attr('transform',function(d,i) { return 'translate(0,'+((d.n-state.n+state.nfacet-1)*L)+')'; });
}
function facet_update(facets, t)
{
facet_move(facets, t);
}
function update_view(state, ticktock)
{
var wheel = d3.select("#wheel");
var facets = wheel.selectAll('g');
if (state.ticktock)
{
var t = d3.transition().duration(300);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd .call(facet_update, t)
.enter()
.call(facet_enter, t)
upd.exit()
.transition(t)
.attr('transform','translate (0,'+(-L)+')')
.remove();
}
else
{
// tock
var t = d3.transition().duration(100);
var t2 = t.transition().duration(100);
var upd = facets
.data(state.wheel, function(d,i) { return d.n; });
upd.call(facet_update, t)
.enter()
.call(facet_enter, t);
}
}
var tmr = d3.timer(function(elapsed) {
var do_something = false;
while (elapsed >= state.nexttick)
{
do_something = true;
state.nexttick += state.ticksize;
}
if (do_something && !(d3.select('#pause').property('checked') ))
{
state.ticktock = !state.ticktock;
update_state(state);
update_view(state);
state.init = false;
}
} );
});
</script>
</head>
<body>
<div id='wheel-container' ></div>
<form class="">
<input type="checkbox" id="pause" name="pause">pause</input>
</form>
<div id='ticktock' class='hidden'></div>
</body>
</html>

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

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!!

HTML5 Image Upload to Page Polyfill Demo [duplicate]

I need help setting up Jadriens FileReader.js. I have set up everything as I think this polyfill works. But the callback that fires when everything is initiated doesn't fire in IE9. This is my markup:
<body>
<div class="main">
<canvas id="mainCanvas" width="600" height="600"></canvas><br />
<div id="fileReaderSWFObject"></div>
<input type="file" id="imageLoader" name="imageLoader" /><br />
<input id="text" type="text" placeholder="some text...">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script>
<!--[if lt IE 10]>
<script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script src="js/vendor/jquery-ui-1.8.23.custom.min.js"></script>
<script src="js/vendor/jquery.FileReader.min.js"></script>
<![endif]-->
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
</body>
And this is main.js:
$(function () {
// Variables
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
var canvasCenter = canvas.width / 2;
var img = '';
var newImageHeight = 0;
var logoX = 0;
var padding = 50;
// Functions
var flushCanvas = function () {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.width + padding);
if (img !== '') {
context.drawImage(img, padding, padding, canvas.width - (padding * 2), newImageHeight - (padding * 2));
}
setText();
};
var setText = function () {
context.textAlign = 'center';
context.fillStyle = '#fff';
context.font = '22px sans-serif';
context.textBaseline = 'bottom';
context.fillText($('#text').val(), canvasCenter, canvas.height - 40);
};
// Init
if ($.browser.msie && $.browser.version <= 9) {
swfobject.embedSWF('filereader.swf', 'fileReaderSWFObject', '100%', '100%', '10', 'expressinstall.swf');
$('#imageLoader').fileReader({
id: 'fileReaderSWFObject',
filereader: 'filereader.swf',
expressInstall: 'expressInstall.swf',
debugMode: true,
callback: function () { console.log('filereader ready'); }
});
}
$('#imageLoader').change(function (e) {
if ($.browser.msie && $.browser.version <= 9) {
console.log(e.target.files[0].name);
} else {
var reader = new FileReader();
reader.onload = function (event) {
img = new Image();
img.onload = function () {
newImageHeight = (img.height / img.width) * (canvas.width);
canvas.height = newImageHeight + padding;
flushCanvas();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
});
$('#text').keyup(function (e) {
flushCanvas();
});
});
A lot of code but i thought a context might help. The important lines are just below the Init comment. The callback-function in the .fileReader init options never fires. It does fire in other modern browsers though (if you remove the if statement).
There are a combination of mistakes here.
Jahdriens filereader takes care of the embedding of flash. Just include the swfObject library.
Browser sniffing = bad idea. Modernizr = good idea.
Make sure you have flash for IE installed :(
My final code looks like this and it works perfect. HTML:
<canvas id="mainCanvas" width="600" height="600"></canvas><br />
<a id="imageLoaderButton" class="button upload">load image</a>
<input type="file" id="imageLoader" class="hidden" name="imageLoader" />
<input id="text" type="text" placeholder="some text...">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.1.min.js"><\/script>')</script>
<script src="js/main.js"></script>
+ link in a custom build of modernizr in the head. (click "non core detects" -> "file-api" when creating you custom build)
And my JS:
$(function () {
Modernizr.load({
test: Modernizr.filereader,
nope: ['js/vendor/swfobject.js', 'js/vendor/jquery-ui-1.8.23.custom.min.js', 'js/vendor/jquery.FileReader.min.js'],
complete: function () {
if (!Modernizr.filereader) {
$('#imageLoaderButton').fileReader({
id: 'fileReaderSWFObject',
filereader: 'filereader.swf',
expressInstall: 'expressInstall.swf',
debugMode: true,
callback: function () {
$('#imageLoaderButton').show().on('change', read);
}
});
} else {
$('#imageLoaderButton').show().on('click', function () {
$('#imageLoader').trigger('click').on('change', read);
});
}
}
});
// Variables
var canvas = document.getElementById('mainCanvas');
var context = canvas.getContext('2d');
var canvasCenter = canvas.width / 2;
var img = '';
var padding = 50;
// Functions
var flushCanvas = function () {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.width + padding);
if (img !== '') {
context.drawImage(img, padding, padding, canvas.width - (padding * 2), newImageHeight - (padding * 2));
}
setText();
};
var setText = function () {
context.textAlign = 'center';
context.fillStyle = '#fff';
context.font = '22px sans-serif';
context.textBaseline = 'bottom';
context.fillText($('#text').val(), canvasCenter, canvas.height - 40);
};
var read = function (e) {
if (typeof FileReader !== 'undefined') {
var reader = new FileReader();
reader.onload = function (event) {
img = new Image();
img.onload = function () {
newImageHeight = (img.height / img.width) * (canvas.width);
canvas.height = newImageHeight + padding;
flushCanvas();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
};
$('#text').keyup(function (e) {
flushCanvas();
});
});
The problem with IE9 is you need flash player to be installed first also there are many features not supported by IE9

accessing webcam in web pages

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/