HTML 5.0 websocket not working - html

I have tried to make an application using node js
"GameClient.html"
<html>
<head>
<script language="JavaScript" src="js/jquery-1.8.3.min.js"></script>
<head>
<body>
<script src="http://localhost:8888/socket.io/socket.io.js" type="text/javascript"></script>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
var canvas = $("#canvas");
if(canvas[0].getContext){
var ctx = canvas[0].getContext("2d");
} else {
alert("canvas problem");
}
$(document).ready(function() {
var down = false;
$("#canvas").mousedown(function(){
down = true;
ctx.beginPath();
socket.send("dn");
});
$("#canvas").mouseup(function(){
down = false;
socket.send("up");
});
$("#canvas").mousemove(function(e){
if(down == true){
ctx.strokeStyle = 'green';
ctx.lineWidth = 20;
ctx.lineJoin = "round";
ctx.lineTo(e.pageX + 1, e.pageY + 1);
ctx.stroke();
socket.send(e.pageX + "1" + e.pageY);
}
});
//====================================================================
var socket = io.connect('localhost', {port: 8888});
socket.on('message', function(msg){
var mh=msg.n;
alert(mh);
if(mh == "dn"){
ctx.beginPath();
$('#add').append(" dn ");
}else if( mh == "up"){
$('#add').append(" up ");
} else{
arr = mh.split(":");
}
ctx.strokeStyle = '#000';
ctx.lineWidth = 20;
ctx.lineJoin = "round";
ctx.lineTo(arr[0],arr[1]);
ctx.stroke();
});
});
</script>
<body>
</html>
Socket-Server.js
// Require HTTP module (to start server) and Socket.IO
var http = require('http')
var io = require('socket.io');
var server = http.createServer(function(req, res){
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8888,'localhost');
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(socket){
socket.on('message',function(msg){
socket.broadcast.emit('message', {n:'Stopped'});
});
socket.on('disconnect',function(){
console.log('Server has disconnected');
});
socket.on('iran', function(data){
console.log("**************" + data.todo + "******************");
});
});
I am not getting the alert(mh); on the GameClient.html
Any suggestions please.

Your server code should be like this:
// Require HTTP module (to start server) and Socket.IO
var http = require('http')
var io = require('socket.io').listen(8888);
// Add a connect listener
io.sockets.on('connection', function(socket){
socket.on('message',function(msg){
socket.broadcast.emit('message', {n:msg});
});
socket.on('disconnect',function(){
console.log('Server has disconnected');
});
socket.on('iran', function(data){
console.log("**************" + data.todo + "******************");
});
});
also please change your html function to $("#canvas").mousemove(function(e) as well
$("#canvas").mousemove(function(e){
if(down == true){
ctx.strokeStyle = 'green';
ctx.lineWidth = 20;
ctx.lineJoin = "round";
ctx.lineTo(e.pageX + 1, e.pageY + 1);
ctx.stroke();
socket.send(e.pageX + ":" + e.pageY);
}
Try this and it will solve your problem.

Related

html5 - canvas mouse up event not triggered

In canvas, mousedown and mousemove works fine, but mouseup event not been triggered in below sample:
<!DOCTYPE html>
<html> <head> <style type="text/css"> body {background: #eee;} </style> </head>
<body>
<div style="float:left;">
<canvas id="video-canvas" width=320 height=240 style="background:#000;"></canvas>
</div>
<pre align="left" id="log"></pre>
<script>
function Logger(id) {this.el = document.getElementById('log');}
Logger.prototype.log = function(msg) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(msg));
fragment.appendChild(document.createElement('br'));
this.el.appendChild(fragment);
};
Logger.prototype.clear = function() {this.el.textContent = '';};
var logger = new Logger('log');
</script>
<script type="text/javascript">
var logelem = document.getElementById("log");
var canvas = document.getElementById('video-canvas');
function getMousePos(canvasDom, mouseEvent) {
var rect = canvasDom.getBoundingClientRect();
var scaleX = canvas.width / rect.width;
var scaleY = canvas.height / rect.height;
var x = (mouseEvent.clientX - rect.left)*scaleX;
var y = (mouseEvent.clientY - rect.top)*scaleY;
return {
x: mouseEvent.clientX - rect.left,
y: mouseEvent.clientY - rect.top
};
}
canvas.addEventListener("mousedown", function (e) {
var mousePos = getMousePos(canvas, e);
logger.log("down " + mousePos.x + "," + mousePos.y);
}, false);
canvas.addEventListener("mouseup", function (e) {
logger.log("up " + mousePos.x + "," + mousePos.y);
}, false);
canvas.addEventListener("mousemove", function (e) {
//logger.log("move " + mousePos.x + "," + mousePos.y);
var mousePos = getMousePos(canvas, e);
}, false);
</script>
</body>
</html>

How to apply z-index for fabric js handlers

setTimeout(function () {
var myImg = document.querySelector("#background");
var realWidth = myImg.naturalWidth;
var realHeight = myImg.naturalHeight;
$("canvas").attr("width", realWidth);
$("canvas").attr("height", realHeight);
var source = document.getElementById('background').src;
var canvas = new fabric.Canvas('canvas');
canvas.width = realWidth;
canvas.height = realHeight;
var ctx = canvas.getContext('2d');
document.getElementById('file').addEventListener("change", function (e) {
var file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (f) {
var data = f.target.result;
fabric.Image.fromURL(data, function (img) {
var oImg = img.set({
left: 320
, top: 180
, angle: 00
, width: 200
, height: 200
});
canvas.add(oImg).renderAll();
var a = canvas.setActiveObject(oImg);
var dataURL = canvas.toDataURL({
format: 'png'
, quality: 0.8
});
});
};
reader.readAsDataURL(file);
});
canvas.setOverlayImage(source, canvas.renderAll.bind(canvas), {
backgroundImageOpacity: 0.5
, backgroundImageStretch: false
});
canvas.on('mouse:over', function (e) {
canvas.item(0).hasBorders = true;
canvas.item(0).hasControls = true;
canvas.setActiveObject(canvas.item(0));
});
canvas.on('mouse:out', function (e) {
canvas.item(0).hasBorders = false;
canvas.item(0).hasControls = false;
canvas.setActiveObject(canvas.item(0));
});
canvas.renderAll();
}, 2000);
$("#save").click(function () {
function blobCallback(iconName) {
return function (b) {
var a = document.getElementById('download');
a.download = iconName + ".jpg";
a.href = window.URL.createObjectURL(b);
}
}
canvas.toBlob(blobCallback('wallpaper'), 'image/vnd.microsoft.jpg', '-moz-parse-options:format=bmp;bpp=32');
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cricmovie.com/bb-asserts/js/fabric.min.js"></script>
<body>
<div class="container"> <img src="http://cricmovie.com/bb-asserts/images/person.png" id="background" class="hide">
<input type="file" id="file">
<br />
<canvas id="canvas" class="img-responsive"></canvas>
</div>
<div class="container"> <a class="btn btn-primary" id="save">Save</a> <a class="btn btn-primary" id="download">Download</a> </div>
</body>
I am using fabric js to build a facemask application when i have two images
1) Image without face which is applied to canvas using setOverlayImage method
2) Only head where the user will upload and adjust accordingly.
I have almost done with functionality but I want to show fabric handlers above the first image where now they are hiding behind first image.
Reference Image : Click here for reference Image
Please find the Run Code Snippet
I think all you need to do is specify controlsAboveOverlay when you get the fabric instance.
var canvas = new fabric.Canvas('canvas', {
controlsAboveOverlay : true
});

How to save a image to HTML5 filesystem with the url of image

I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can't find the way to get a image by web url and then store it in HTML5 file system.
This is my code, but it's wrong.
lib.ajax.get(file , function(xhr, data){
if(xhr.status == 200){
fs.root.getFile("test.jpg", {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
bb.append(data);
fileWriter.write(bb.getBlob('image/jpeg'));
callback && callback("test.jpg");
}, errorHandler);
}, errorHandler);
}
});
The problem is that browser will parse xhr response data as UTF-8,
So the point is to override MimeType:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
var photoUrl = 'http://localhost:3000/image.jpg';
xhr.open('GET', photoUrl, true);
// This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');
function stringToBinary(response) {
var byteArray = new Uint8Array(response.length);
for (var i = 0; i < response.length; i++) {
byteArray[i] = response.charCodeAt(i) & 0xff;
}
return byteArray
}
function onInitFs(fs) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(event) {
$('body').append('<img src="' + fileEntry.toURL() + '"/>');
}
buffer = stringToBinary(xhr.response);
var blob = new Blob([ buffer ], { type: 'image/jpeg' } )
fileWriter.write(blob);
}, errorHandler );
});
}
}
xhr.send();
}
var errorHandler = function(err) {
console.log(err);
}
$(function() {
webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) {
requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler)
}, errorHandler)
})
Here the function I use.
It use Blob constructor so it works on latest Chrome (thats lacks deprecated BlobBuilder) and works also on old iOS 6 that lacks 'blob' for xhr.responseType.
In comments you also see code for the deprecated BlobBuilder.
Notice: you are using XHR so CORS must be enabled!
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);
function onFileSystemSuccess(fileSystem) {
fs = fileSystem;
console.log('File system initialized');
saveAsset('http://www.example-site-with-cors.com/test.png');
}
function saveAsset(url, callback, failCallback) {
var filename = url.substring(url.lastIndexOf('/')+1);
// Set callback when not defined
if (!callback) {
callback = function(cached_url) {
console.log('download ok: ' + cached_url);
};
}
if (!failCallback) {
failCallback = function() {
console.log('download failed');
};
}
// Set lookupTable if not defined
if (!window.lookupTable)
window.lookupTable = {};
// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {
// Save this file in the path to URL lookup table.
lookupTable[filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};
writer.onerror = failCallback;
// var bb = new BlobBuilder();
var blob = new Blob([xhr.response], {type: ''});
// bb.append(xhr.response);
writer.write(blob);
// writer.write(bb.getBlob());
}, failCallback);
}, failCallback);
});
xhr.addEventListener('error', failCallback);
xhr.send();
return filename;
}
function fail(evt) {
console.log(evt.target.error.code);
}
On a modern browser supporting XMLHttpRequest Level 2 the method documented in this answer should work.
The relevant standard is explained in this blog post
The trick is to use xhr.responseType = 'blob'
var fs = .... // your fileSystem
function download(fs,url,file,win,fail) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status === 200){
fs.root.getFile(file,{create:true},function(fileEntry){
fileEntry.createWriter(function(writer){
writer.onwriteend = win;
writer.onerror = fail;
writer.write(xhr.response);
})
},fail)
} else {
fail(xhr.status);
}
}
};
xhr.send();
return xhr;
};
Based on cordova-promise-fs (disclosure: I'm the author)
I find a way to do this.
use canvans.toDataURL to transfer data format.
var img = new Image();
var cvs = document.createElement('canvas');
var ctx = cvs.getContext("2d");
img.src = file;
img.onload = function(){
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0);
var imd = cvs.toDataURL(contentType[extname]);
var ui8a = convertDataURIToBinary(imd);
var bb = new BlobBuilder();
bb.append(ui8a.buffer);
fs.root.getFile(path, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
callback && callback("test.jpg");
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
fileWriter.write(bb.getBlob(contentType[extname]));
});
});
};
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
I get help from here jsfiddle

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/