Webcam.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /**
  2. * Provides access to the Webcam (if available)
  3. * @class Phaser.Plugin.Webcam
  4. */
  5. Phaser.Plugin.Webcam = function (game, parent) {
  6. Phaser.Plugin.call(this, game, parent);
  7. if (!game.device.getUserMedia)
  8. {
  9. return false;
  10. }
  11. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  12. this.context = null;
  13. this.stream = null;
  14. this.video = document.createElement('video');
  15. this.video.autoplay = true;
  16. this.onConnect = new Phaser.Signal();
  17. this.onError = new Phaser.Signal();
  18. };
  19. Phaser.Plugin.Webcam.prototype = Object.create(Phaser.Plugin.prototype);
  20. Phaser.Plugin.Webcam.prototype.constructor = Phaser.Plugin.Webcam;
  21. Phaser.Plugin.Webcam.prototype.start = function (width, height, context) {
  22. // console.log('Webcam start', width, height);
  23. this.context = context;
  24. if (!this.stream)
  25. {
  26. navigator.getUserMedia( { video: { mandatory: { minWidth: width, minHeight: height } } }, this.connectCallback.bind(this), this.errorCallback.bind(this));
  27. }
  28. };
  29. Phaser.Plugin.Webcam.prototype.stop = function () {
  30. if (this.stream)
  31. {
  32. this.stream.stop();
  33. this.stream = null;
  34. }
  35. };
  36. Phaser.Plugin.Webcam.prototype.connectCallback = function (stream) {
  37. this.stream = stream;
  38. this.video.src = window.URL.createObjectURL(this.stream);
  39. this.onConnect.dispatch(this.video);
  40. };
  41. Phaser.Plugin.Webcam.prototype.errorCallback = function (event) {
  42. this.onError.dispatch(event);
  43. };
  44. Phaser.Plugin.Webcam.prototype.grab = function (context, x, y) {
  45. if (this.stream)
  46. {
  47. context.drawImage(this.video, x, y);
  48. }
  49. };
  50. Phaser.Plugin.Webcam.prototype.update = function () {
  51. if (this.stream)
  52. {
  53. this.context.drawImage(this.video, 0, 0);
  54. }
  55. };
  56. /**
  57. * @name Phaser.Plugin.Webcam#active
  58. * @property {boolean} active - Is this Webcam plugin capturing a video stream or not?
  59. * @readonly
  60. */
  61. Object.defineProperty(Phaser.Plugin.Webcam.prototype, "active", {
  62. get: function() {
  63. return (this.stream);
  64. }
  65. });