getUserMedia on click only - getusermedia

I'm trying to capture video/photo from webcam. I've foun a script working, but I would like to start the camera access only on button click. With this script it will start immediatly (I don't want to). How can I bind this event on click please?
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 487, 365);
});
}, false);

You need to call getUserMedia in a click handler instead of during the DOM content loaded event.
I took the code in your question, and modified it:
Made it part of a whole html document so I could test it
Wrapped the code that starts the camera in a function, called startCamera
Added a "start camera" button. You could start the camera with the snap button is clicked, but that didn't really make sense to me.
Added a click listener to the "start camera" button, which simply executes the startCamera function
Here's the code:
<html>
<body>
<canvas id="canvas"></canvas>
<video id="video"></video>
<button id="startCamera">Start camera</button>
<button id="snap">Take snapshot</button>
<script>
window.addEventListener("DOMContentLoaded", function() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
function startCamera() {
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 487, 365);
});
// Trigger starting the camera
document.getElementById("startCamera").addEventListener("click", function() {
startCamera();
});
}, false);
</script>
</body>
</html>

Try This code. Also try to run this from a virtual directory.
<html>
<head>
<script type="text/javascript">
function doGetUserMedia() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canv"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 487, 365);
});
}
</script>
</head>
<body>
<button onclick="doGetUserMedia()">Start Camera</button>
<video id="video" width="487" height="365"></video>
<button id="snap">Take snapshot</button>
<canvas id="canv" width="487" height="365"></canvas>
</body>
</html>

You can try something like that:
<html>
<head>
<script type="text/javascript">
function doGetUserMedia() {
// Grab elements, create settings, etc.
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
video = document.getElementById("video"),
videoObj = { "video": true },
errBack = function(error) {
console.log("Video capture error: ", error.code);
};
// Put video listeners into place
if(navigator.getUserMedia) { // Standard
navigator.getUserMedia(videoObj, function(stream) {
video.src = stream;
video.play();
}, errBack);
} else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
navigator.webkitGetUserMedia(videoObj, function(stream){
video.src = window.webkitURL.createObjectURL(stream);
video.play();
}, errBack);
}
// Trigger photo take
document.getElementById("snap").addEventListener("click", function() {
context.drawImage(video, 0, 0, 487, 365);
});
}
</script>
</head>
<body>
<button onclick="doGetUserMedia()">Click me</button>
</body>
</html>

Related

pause facebook video on scroll

I am trying to pause facebook video on scroll but its not working below is my code. It gives error pause of undefined. Is there any other way?
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '6296624552155',
xfbml : true,
version : 'v3.2'
});
var my_video_player;
FB.Event.subscribe('xfbml.ready', function(msg) {
if (msg.type === 'video') {
jQuery(window).scroll(function() {
console.log('test');
my_video_player = msg.instance;
my_video_player.pause() ;
});
}
});
};
</script>
<div id="fb-root"></div>
<script async defer src="https://connect.facebook.net/en_US/sdk.js"></script>

Capture Popup page content through CasperJS or PhantomJS

A.html
<input type="submit" name="testLabel" value="Print Test" id="testLabel" onclick="myFunction('<?php echo $dynamic_page;?>')" >
<script>
function myFunction(page) {
var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
window.open(page, "_blank",strWindowFeatures);
}
</script>
CasperJS code
var casper = require('casper').create();
casper.start('http://localhost/test/a.html', function() {
this.echo(this.getTitle());
});
casper.thenClick('#testLabel');
casper.then(function() {
this.capture('page.png');
});
casper.run();
I have also try with phantomjs but i am not able to capture b.html page in page.png
Note : Popup page name is not fixed.
// this will set the popup DOM as the main active one only for time the
// step closure being executed
casper.withPopup(0, function() {
this.test.assertTitle('Popup title');
});
Complete code
var casper = require('casper').create();
casper.start('http://localhost/test/a.html', function () {
this.echo(this.getTitle());
});
casper.thenClick('#testLabel');
casper.waitForPopup(0, function () {
this.echo('Popup');
});
casper.then(function () {
this.capture('page.png');
});
casper.run();
Read more about waitForPopup
There is waitForPopup and withPopup methods so your code would look like this
var casper = require('casper').create();
casper.start('http://localhost/test/a.html', function() {
this.echo(this.getTitle());
});
casper.thenClick('#testLabel');
casper.waitForPopup(/.\.html$/, function() {
this.echo('Popup')
});
casper.withPopup(0, function() {
this.capture('page.png');
});
casper.run();

mithril.js stuck in loop calling controller

I'm trying to POST a token and display the results as an ordered list. I would like the list to update onchange of the input. On page load the request POST is infinitely looping with error:
TypeError: ctrl.keys(...) is undefined
I suspect that my assumptions of how the data binding on the controller works are completely wrong.
//component
var tISM = {};
//model
tISM = {
Key: function(data) {
this.Id = m.prop(data.Id);
this.Name = m.prop(data.Name);
this.CreationTime = m.prop(data.CreationTime);
},
keys: function(token) {
return m.request({
method: "POST",
url: "key/list",
data: { "token": token },
type: tISM.Key
})
},
};
//controller
tISM.controller = function() {
// when this controller is updated perform a new POST for data by calling message?
var token = m.prop("xxx")
var keys = function() {
tISM.keys(this.token)
}
return { token, keys }
};
//view
tISM.view = function(ctrl) {
return m("div"), [
m("ol", ctrl.keys().map( function(key, index) {
return m("li", key.Id, key.Name, key.CreationTime)
})),
m("input", {
onchange: m.withAttr("value", ctrl.token)
})
]
};
//initialize
m.mount(document.getElementById("app"), tISM);
<script src="http://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.5/mithril.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Mithril App</title>
<script src="mithril.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
m.request() returns a deferred, not the value itself. I have a snippet below that shows one way of getting the values out. I explicitly replaced the m.request() with deferred calls under the hood, and a timeout rather than a post.
//component
var tISM = {};
//model
tISM = {
Key: function(data) {
this.Id = m.prop(data.Id);
this.Name = m.prop(data.Name);
this.CreationTime = m.prop(data.CreationTime);
},
keys: function(token) {
m.startComputation()
var d = m.deferred();
setTimeout(function() {
d.resolve([1,2,3]);
m.endComputation();
}, 1000);
return d.promise;
}
};
//controller
tISM.controller = function() {
// when this controller is updated perform a new POST for data by calling message?
var token = m.prop("xxx")
var keys = m.prop([]);
tISM.keys(this.token).then(keys)
return {
token: token,
keys: keys
}
return { token, keys }
};
//view
tISM.view = function(ctrl) {
return m("div"), [
m("ol", ctrl.keys().map( function(key, index) {
return m("li", key.Id, key.Name, key.CreationTime)
})),
m("input", {
onchange: m.withAttr("value", ctrl.token)
})
]
};
//initialize
m.mount(document.getElementById("app"), tISM);
<script src="http://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.5/mithril.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Mithril App</title>
<script src="mithril.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
My problem was I don't know javascript. This works:
//component
var tISM = {};
//model
tISM.Key = function(data) {
this.Id = m.prop(data.Id);
this.Name = m.prop(data.Name);
this.CreationTime = m.prop(data.CreationTime);
}
tISM = {
keys: function(token) {
return m.request({
method: "POST",
url: "key/list",
data: { "token": token },
type: tISM.Key
})
},
};
//controller
tISM.controller = function() {
this.token = m.prop("")
this.keys = m.prop([])
this.updateToken = function(token) {
this.token(token)
tISM.keys(this.token).then(this.keys)
}.bind(this)
};
//view
tISM.view = function(ctrl) {
return m("div"), [
m("input", {
oninput: m.withAttr("value", ctrl.updateToken)
}),
m("ol", ctrl.keys().map( function(key, index) {
return m("li", key.Id, key.Name, key.CreationTime)
})),
]
};
//initialize
m.mount(document.getElementById("app"), tISM);

As to the progress bar videojs player to make draggable slider?

As to the progress bar videojs player to make draggable slider? like here http://take.ms/2m2cW
var down = false;
me.controlBar.progressControl.on('mousedown', function() { down = true; });
me.controlBar.progressControl.on('mouseup', function() { down = false; });
me.controlBar.progressControl.on('mousemove', function(e) {
if(down) {
console.log(this.seekBar.update());
}
});

Bind Ckeditor value to model text in AngularJS and Rails

I want to bind CKEditor text to ng-model text. My View:
<form name="postForm" method="POST" ng-submit="submit()" csrf-tokenized class="form-horizontal">
<fieldset>
<legend>Post to: </legend>
<div class="control-group">
<label class="control-label">Text input</label>
<div class="controls">
<div class="textarea-wrapper">
<textarea id="ck_editor" name="text" ng-model="text" class="fullwidth"></textarea>
</div>
<p class="help-block">Supporting help text</p>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Post</button>
<button class="btn">Cancel</button>
<button class="btn" onclick="alert(ckglobal.getDate())">Cancel123</button>
</div>
</fieldset>
</form>
controller
function PostFormCtrl($scope, $element, $attrs, $transclude, $http, $rootScope) {
$scope.form = $element.find("form");
$scope.text = "";
$scope.submit = function() {
$http.post($scope.url, $scope.form.toJSON()).
success(function(data, status, headers, config) {
$rootScope.$broadcast("newpost");
$scope.form[0].reset();
});
};
$scope.alert1 = function(msg) {
var sval = $element.find("ckglobal");
//$('.jquery_ckeditor').ckeditor(ckeditor);
alert(sval);
};
}
PostFormCtrl.$inject = ["$scope", "$element", "$attrs", "$transclude", "$http", "$rootScope"];
I want to set CKEditor value in $scope.text at the time of form submit.
CKEditor does not update textarea while typing, so you need to take care of it.
Here's a directive that will make ng-model binding work with CK:
angular.module('ck', []).directive('ckEditor', function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ngModel) {
var ck = CKEDITOR.replace(elm[0]);
if (!ngModel) return;
ck.on('pasteState', function() {
scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
});
});
ngModel.$render = function(value) {
ck.setData(ngModel.$viewValue);
};
}
};
});
In html, just use:
<textarea ck-editor ng-model="value"></textarea>
The previous code will update ng-model on every change.
If you only want to update binding on save, override "save" plugin, to not do anything but fire "save" event.
// modified ckeditor/plugins/save/plugin.js
CKEDITOR.plugins.registered['save'] = {
init: function(editor) {
var command = editor.addCommand('save', {
modes: {wysiwyg: 1, source: 1},
readOnly: 1,
exec: function(editor) {
editor.fire('save');
}
});
editor.ui.addButton('Save', {
label : editor.lang.save,
command : 'save'
});
}
};
And then, use this event inside the directive:
angular.module('ck', []).directive('ckEditor', function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ngModel) {
var ck = CKEDITOR.replace(elm[0]);
if (!ngModel) return;
ck.on('save', function() {
scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
});
});
}
};
});
If you simply want to retrieve text in the editor textarea in angular, call CKEDITOR.instances.editor1.getData(); to get the value directly in an angularjs function. See below.
In your html
In the test.controller.js
(function () {
'use strict';
angular
.module('app')
.controller('test', test);
test.$inject = [];
function test() {
//this is to replace $scope
var vm = this;
//function definition
function postJob()
{
vm.Description = CKEDITOR.instances.editor1.getData();
alert(vm.Description);
}
}
})();
the Vojta answer work partly
in this post I found a solution
https://stackoverflow.com/a/18236359/1058096
the final code:
.directive('ckEditor', function() {
return {
require : '?ngModel',
link : function($scope, elm, attr, ngModel) {
var ck = CKEDITOR.replace(elm[0]);
ck.on('instanceReady', function() {
ck.setData(ngModel.$viewValue);
});
ck.on('pasteState', function() {
$scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
});
});
ngModel.$render = function(value) {
ck.setData(ngModel.$modelValue);
};
}
};
})
edit: removed unused brackets
Thanks to Vojta for the excellent directive. Sometimes it doesn't load. Here is a modified version to fix that issue.
angular.module('ck', []).directive('ckEditor', function() {
var calledEarly, loaded;
loaded = false;
calledEarly = false;
return {
require: '?ngModel',
compile: function(element, attributes, transclude) {
var loadIt, local;
local = this;
loadIt = function() {
return calledEarly = true;
};
element.ready(function() {
return loadIt();
});
return {
post: function($scope, element, attributes, controller) {
if (calledEarly) {
return local.link($scope, element, attributes, controller);
}
loadIt = (function($scope, element, attributes, controller) {
return function() {
local.link($scope, element, attributes, controller);
};
})($scope, element, attributes, controller);
}
};
},
link: function($scope, elm, attr, ngModel) {
var ck;
if (!ngModel) {
return;
}
if (calledEarly && !loaded) {
return loaded = true;
}
loaded = false;
ck = CKEDITOR.replace(elm[0]);
ck.on('pasteState', function() {
$scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
});
});
ngModel.$render = function(value) {
ck.setData(ngModel.$viewValue);
};
}
};
});
or if you need it in coffeescript
angular.module('ck', []).directive('ckEditor', ->
loaded = false
calledEarly = false
{
require: '?ngModel',
compile: (element, attributes, transclude) ->
local = #
loadIt = ->
calledEarly = true
element.ready ->
loadIt()
post: ($scope, element, attributes, controller) ->
return local.link $scope, element, attributes, controller if calledEarly
loadIt = (($scope, element, attributes, controller) ->
return ->
local.link $scope, element, attributes, controller
)($scope, element, attributes, controller)
link: ($scope, elm, attr, ngModel) ->
return unless ngModel
if (calledEarly and not loaded)
return loaded = true
loaded = false
ck = CKEDITOR.replace(elm[0])
ck.on('pasteState', ->
$scope.$apply( ->
ngModel.$setViewValue(ck.getData())
)
)
ngModel.$render = (value) ->
ck.setData(ngModel.$viewValue)
}
)
And just for the record if you want to use multiple editors in one page this can come in handy:
mainApp.directive('ckEditor', function() {
return {
restrict: 'A', // only activate on element attribute
scope: false,
require: 'ngModel',
controller: function($scope, $element, $attrs) {}, //open for now
link: function($scope, element, attr, ngModel, ngModelCtrl) {
if(!ngModel) return; // do nothing if no ng-model you might want to remove this
element.bind('click', function(){
for(var name in CKEDITOR.instances)
CKEDITOR.instances[name].destroy();
var ck = CKEDITOR.replace(element[0]);
ck.on('instanceReady', function() {
ck.setData(ngModel.$viewValue);
});
ck.on('pasteState', function() {
$scope.$apply(function() {
ngModel.$setViewValue(ck.getData());
});
});
ngModel.$render = function(value) {
ck.setData(ngModel.$viewValue);
};
});
}
}
});
This will destroy all previous instances of ckeditor and create a new one.
There's now a 'change' event that can be used for this.
Here's a directive I've just created that has a couple of different toolbar config options, I'm using the jQuery adapter to initialize ckeditor. For more info check out this blog post.
(function () {
'use strict';
angular
.module('app')
.directive('wysiwyg', Directive);
function Directive($rootScope) {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
var editorOptions;
if (attr.wysiwyg === 'minimal') {
// minimal editor
editorOptions = {
height: 100,
toolbar: [
{ name: 'basic', items: ['Bold', 'Italic', 'Underline'] },
{ name: 'links', items: ['Link', 'Unlink'] },
{ name: 'tools', items: ['Maximize'] },
{ name: 'document', items: ['Source'] },
],
removePlugins: 'elementspath',
resize_enabled: false
};
} else {
// regular editor
editorOptions = {
filebrowserImageUploadUrl: $rootScope.globals.apiUrl + '/files/uploadCk',
removeButtons: 'About,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Save,CreateDiv,Language,BidiLtr,BidiRtl,Flash,Iframe,addFile,Styles',
extraPlugins: 'simpleuploads,imagesfromword'
};
}
// enable ckeditor
var ckeditor = element.ckeditor(editorOptions);
// update ngModel on change
ckeditor.editor.on('change', function () {
ngModel.$setViewValue(this.getData());
});
}
};
}
})();
Here's a couple of examples of how to use the directive in HTML
<textarea ng-model="vm.article.Body" wysiwyg></textarea>
<textarea ng-model="vm.article.Body" wysiwyg="minimal"></textarea>
And here are the CKEditor scripts I'm including from a CDN plus a couple of extra plugins that I downloaded to enable pasting images from word.
<script src="//cdn.ckeditor.com/4.5.7/full/ckeditor.js"></script>
<script src="//cdn.ckeditor.com/4.5.7/full/adapters/jquery.js"></script>
<script type="text/javascript">
// load extra ckeditor plugins
CKEDITOR.plugins.addExternal('simpleuploads', '/js/ckeditor/plugins/simpleuploads/plugin.js');
CKEDITOR.plugins.addExternal('imagesfromword', '/js/ckeditor/plugins/imagesfromword/plugin.js');
</script>
ES6 example with CKEditor v5.
Register directive using:
angular.module('ckeditor', []).directive('ckEditor', CkEditorDirective.create)
Directive:
import CkEditor from "#ckeditor/ckeditor5-build-classic";
export default class CkEditorDirective {
constructor() {
this.restrict = 'A';
this.require = 'ngModel';
}
static create() {
return new CkEditorDirective();
}
link(scope, elem, attr, ngModel) {
CkEditor.create(elem[0]).then((editor) => {
editor.document.on('changesDone', () => {
scope.$apply(() => {
ngModel.$setViewValue(editor.getData());
});
});
ngModel.$render = () => {
editor.setData(ngModel.$modelValue);
};
scope.$on('$destroy', () => {
editor.destroy();
});
})
}
}