phaser/plugins/Webcam.js

93 lines
1.9 KiB
JavaScript
Raw Normal View History

/**
* Provides access to the Webcam (if available)
*/
Phaser.Plugin.Webcam = function (game, parent) {
2014-03-23 17:08:20 +00:00
Phaser.Plugin.call(this, game, parent);
2014-03-23 17:08:20 +00:00
if (!game.device.getUserMedia)
{
return false;
}
2014-03-23 17:08:20 +00:00
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
2014-03-23 17:08:20 +00:00
this.context = null;
this.stream = null;
2014-03-23 17:08:20 +00:00
this.video = document.createElement('video');
this.video.autoplay = true;
};
Phaser.Plugin.Webcam.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.Webcam.prototype.constructor = Phaser.Plugin.Webcam;
Phaser.Plugin.Webcam.prototype.start = function (width, height, context) {
2014-03-23 17:08:20 +00:00
console.log('Webcam start', width, height);
2014-03-23 17:08:20 +00:00
this.context = context;
2014-03-23 17:08:20 +00:00
if (!this.stream)
{
navigator.getUserMedia( { video: { mandatory: { minWidth: width, minHeight: height } } }, this.connectCallback.bind(this), this.errorCallback.bind(this));
}
};
Phaser.Plugin.Webcam.prototype.stop = function () {
2014-03-23 17:08:20 +00:00
if (this.stream)
{
this.stream.stop();
this.stream = null;
}
};
Phaser.Plugin.Webcam.prototype.connectCallback = function (stream) {
2014-03-23 17:08:20 +00:00
this.stream = stream;
2014-03-23 17:08:20 +00:00
this.video.src = window.URL.createObjectURL(this.stream);
};
Phaser.Plugin.Webcam.prototype.errorCallback = function (e) {
2014-03-23 17:08:20 +00:00
console.log('Video Stream rejected', e);
};
Phaser.Plugin.Webcam.prototype.grab = function (context, x, y) {
2014-03-23 17:08:20 +00:00
if (this.stream)
{
context.drawImage(this.video, x, y);
}
};
Phaser.Plugin.Webcam.prototype.update = function () {
2014-03-23 17:08:20 +00:00
if (this.stream)
{
this.context.drawImage(this.video, 0, 0);
}
};
/**
* @name Phaser.Plugin.Webcam#active
* @property {boolean} active - Is this Webcam plugin capturing a video stream or not?
* @readonly
*/
Object.defineProperty(Phaser.Plugin.Webcam.prototype, "active", {
get: function() {
return (this.stream);
}
});