Skip to content

Instantly share code, notes, and snippets.

@Akiyah
Created August 15, 2013 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akiyah/6240101 to your computer and use it in GitHub Desktop.
Save Akiyah/6240101 to your computer and use it in GitHub Desktop.
forked: getUserMedia APIを使ってカメラを表示させてみる
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #fdd;
font: 30px sans-serif;
}
<div id="wrapper">
<button id="capture">capture</button>
<button id="stop">stop</button>
</div>
<video autoplay width="320" height="240"></video>
<img src="" width="320" height="240" >
<canvas style="" width="640" height="480"></canvas>
// forked from Akiyah's "getUserMedia APIを使ってカメラを表示させてみる" http://jsdo.it/Akiyah/AkLuC
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');
var localMediaStream = null;
//カメラ使えるかチェック
var hasGetUserMedia = function() {
return !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
}
//エラー
var onFailSoHard = function(e) {
console.log('エラー!', e);
};
//カメラ画像キャプチャ
var snapshot = function() {
if (localMediaStream) {
ctx.drawImage(video, 0, 0);
document.querySelector('img').src = canvas.toDataURL('image/webp');
}
}
if (hasGetUserMedia()) {
console.log("カメラ OK");
} else {
alert("未対応ブラウザです。");
}
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia({video: true}, function(stream) {
video.src = window.URL.createObjectURL(stream);
localMediaStream = stream;
}, onFailSoHard);
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
function render() {
ctx.drawImage(video, 0, 0);
document.querySelector('img').src = canvas.toDataURL('image/webp');
var pixels = ctx.getImageData(0, 0, 640, 480);
var d = pixels.data;
var r = 0;
var g = 0;
var b = 0;
var a = 0;
for (var i = 0; i < d.length; i+=4) {
r += d[i];
g += d[i+1];
b += d[i+2];
a += d[i+3];
}
console.log(r,g,b,a);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
//ボタンイベント
$("#capture").click(function() {
snapshot();
});
$("#stop").click(function() {
localMediaStream.stop();
});
$("video").click(function() {
snapshot();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment