Created
July 4, 2015 07:22
-
-
Save chikoski/01367f53d4db40eea69f to your computer and use it in GitHub Desktop.
クリックした範囲の色の平均値を表示するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#preview{ | |
display: none; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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