Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created July 4, 2015 07:22
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 chikoski/01367f53d4db40eea69f to your computer and use it in GitHub Desktop.
Save chikoski/01367f53d4db40eea69f to your computer and use it in GitHub Desktop.
クリックした範囲の色の平均値を表示するプログラム
#preview{
display: none;
}
const WINDOW_SIZE = 16;
var canvas = document.querySelector("#canvas");
var video = document.querySelector("#preview");
var log = document.querySelector("#log");
var ctx = canvas.getContext("2d");
function checkColor(event){
var position = {
x: event.layerX - canvas.offsetLeft,
y: event.layerY - canvas.offsetTop
};
var topLeft = {
x: Math.min(0, position.x - WINDOW_SIZE / 2),
y: Math.min(0, position.y - WINDOW_SIZE / 2)
};
var pixels = ctx.getImageData(topLeft.x, topLeft.y,
WINDOW_SIZE, WINDOW_SIZE);
var color = [0, 0, 0];
for(var i = 0; i < pixels.data.length; i = i + 4){
color[0] += pixels.data[i];
color[1] += pixels.data[i + 1];
color[2] += pixels.data[i + 2];
}
color = [Math.floor(color[0] / pixels.data.length * 4),
Math.floor(color[1] / pixels.data.length * 4),
Math.floor(color[2] / pixels.data.length * 4)];
log.textContent = "平均値 = " +
color[0] + "," +
color[1] + "," +
color[2];
}
function update(){
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
requestAnimationFrame(update);
}
function streamAcquired(stream){
video.src = window.URL.createObjectURL(stream);
video.play();
update();
}
function error(msg){
console.log(msg);
}
function initialize(){
navigator.getUserMedia =
navigator.getUserMedia ||
navigator.mozGetUserMedia;
navigator.getUserMedia({video: true, audio:false},
streamAcquired,
error);
}
canvas.addEventListener("click", checkColor);
initialize();
<!doctype html>
<html>
<head>
<title>カメラで色を調べる</title>
<meta charset="utf-8">
<link rel="stylesheet" href="app.css">
</head>
<body>
<video id="preview"></video>
<canvas id="canvas" width="800" height="600"></canvas>
<p id="log"></p>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment