问题
Is it possible to get the RGB value pixel under the mouse? Is there a complete example of this? Here\'s what I have so far:
<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>
回答1:
Here's a complete, self-contained example. First, use the following HTML:
<canvas id="example" width="200" height="60"></canvas>
<div id="status"></div>
The relevant 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);
});
The code above assumes the presence of jQuery and the following utility functions:
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);
}
See it in action on JSFIDDLE:
- http://jsfiddle.net/DV9Bw/1/
回答2:
I know this is an old question, but here's an alternative. I'd store that image data in an array, then, on mouse move event over the canvas:
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]
A lot easier than getting the imageData everytime.
回答3:
Merging various references found here in StackOverflow (including the article above) and in other sites, I did so using javascript and 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.
回答4:
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);
回答5:
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);
};
回答6:
You can try color-sampler. It's an easy way to pick color in a canvas. See demo.
回答7:
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.
回答8:
@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.)
来源:https://stackoverflow.com/questions/6735470/get-pixel-color-from-canvas-on-mouseover