마우스 오버시 캔버스에서 픽셀 색상 가져 오기
마우스 아래에서 RGB 값 픽셀을 얻을 수 있습니까? 이것에 대한 완전한 예가 있습니까? 지금까지 내가 가진 내용은 다음과 같습니다.
<script>
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.src = 'Your URL';
img.onload = function(){
ctx.drawImage(img,0,0);
};
canvas.onmousemove = function(e) {
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
var c = ctx.getImageData(mouseX, mouseY, 1, 1).data;
$('#ttip').css({'left':mouseX+20, 'top':mouseY+20}).html(c[0]+'-'+c[1]+'-'+c[2]);
};
}
</script>
다음은 완전한 독립형 예제입니다. 먼저 다음 HTML을 사용하십시오.
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>
관련 JavaScript :
// set up some sample squares
var example = document.getElementById('example');
var context = example.getContext('2d');
context.fillStyle = "rgb(255,0,0)";
context.fillRect(0, 0, 50, 50);
context.fillStyle = "rgb(0,0,255)";
context.fillRect(55, 0, 50, 50);
$('#example').mousemove(function(e) {
var pos = findPos(this);
var x = e.pageX - pos.x;
var y = e.pageY - pos.y;
var coord = "x=" + x + ", y=" + y;
var c = this.getContext('2d');
var p = c.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
$('#status').html(coord + "<br>" + hex);
});
위 코드는 jQuery와 다음 유틸리티 함수가 있다고 가정합니다.
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
JSFIDDLE에서 실제로 확인하십시오.
나는 이것이 오래된 질문이라는 것을 알고 있지만 여기에 대안이 있습니다. 이미지 데이터를 배열에 저장 한 다음 캔버스 위로 마우스 이동 이벤트를 수행합니다.
var index = (Math.floor(y) * canvasWidth + Math.floor(x)) * 4
var r = data[index]
var g = data[index + 1]
var b = data[index + 2]
var a = data[index + 3]
매번 imageData를 얻는 것보다 훨씬 쉽습니다.
여기 StackOverflow (위의 기사 포함)와 다른 사이트에서 발견 된 다양한 참조를 병합하여 javascript와 JQuery를 사용했습니다.
<html>
<body>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script src="jquery.js"></script>
<script type="text/javascript">
window.onload = function(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'photo_apple.jpg';
context.drawImage(img, 0, 0);
};
function findPos(obj){
var current_left = 0, current_top = 0;
if (obj.offsetParent){
do{
current_left += obj.offsetLeft;
current_top += obj.offsetTop;
}while(obj = obj.offsetParent);
return {x: current_left, y: current_top};
}
return undefined;
}
function rgbToHex(r, g, b){
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
$('#myCanvas').click(function(e){
var position = findPos(this);
var x = e.pageX - position.x;
var y = e.pageY - position.y;
var coordinate = "x=" + x + ", y=" + y;
var canvas = this.getContext('2d');
var p = canvas.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
alert("HEX: " + hex);
});
</script>
<img src="photo_apple.jpg"/>
</body>
</html>
This is my complete solution. Here I only used canvas and one image, but if you need to use <map> over the image, it's possible too.
Quick Answer
context.getImageData(x, y, 1, 1).data; returns an rgba array. e.g. [50, 50, 50, 255]
Here's a version of @lwburk's rgbToHex function that takes the rgba array as an argument.
function rgbToHex(rgb){
return '#' + ((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]).toString(16);
};
calling getImageData every time will slow the process ... to speed up things i recommend store image data and then you can get pix value easily and quickly, so do something like this for better performance
// keep it global
let imgData = false; // initially no image data we have
// create some function block
if(imgData === false){
// fetch once canvas data
var ctx = canvas.getContext("2d");
imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
}
// Prepare your X Y coordinates which you will be fetching from your mouse loc
let x = 100; //
let y = 100;
// locate index of current pixel
let index = (y * imgData.width + x) * 4;
let red = imgData.data[index];
let green = imgData.data[index+1];
let blue = imgData.data[index+2];
let alpha = imgData.data[index+3];
// Output
console.log('pix x ' + x +' y '+y+ ' index '+index +' COLOR '+red+','+green+','+blue+','+alpha);
You can try color-sampler. It's an easy way to pick color in a canvas. See demo.
I have a very simple working example of geting pixel color from canvas.
First some basic HTML:
<canvas id="myCanvas" width="400" height="250" style="background:red;" onmouseover="echoColor(event)">
</canvas>
Then JS to draw something on the Canvas, and to get color:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);
function echoColor(e){
var imgData = ctx.getImageData(e.pageX, e.pageX, 1, 1);
red = imgData.data[0];
green = imgData.data[1];
blue = imgData.data[2];
alpha = imgData.data[3];
console.log(red + " " + green + " " + blue + " " + alpha);
}
Here is a working example, just look at the console.
@Wayne Burkett's answer is good. If you wanted to also extract the alpha value to get an rgba color, we could do this:
var r = p[0], g = p[1], b = p[2], a = p[3] / 255;
var rgba = "rgb(" + r + "," + g + "," + b + "," + a + ")";
I divided the alpha value by 255 because the ImageData object stores it as an integer between 0 - 255, but most applications (for example, CanvasRenderingContext2D.fillRect()) require colors to be in valid CSS format, where the alpha value is between 0 and 1.
(Also remember that if you extract a transparent color and then draw it back onto the canvas, it will overlay whatever color is there previously. So if you drew the color rgba(0,0,0,0.1) over the same spot 10 times, it would be black.)
참고URL : https://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover
'IT TIP' 카테고리의 다른 글
| 투영과 선택이란 무엇입니까? (0) | 2020.10.31 |
|---|---|
| REST 리소스 URL의 쿼리 문자열 (0) | 2020.10.31 |
| 배경 크기를 조정하지 않고 Android 버튼의 히트 영역을 늘리는 방법은 무엇입니까? (0) | 2020.10.31 |
| Java 리플렉션은 모든 개인 필드를 가져옵니다. (0) | 2020.10.31 |
| 선택 쿼리에서 자동 증가 필드를 생성하는 방법 (0) | 2020.10.31 |