我试图通过点击色轮图像来获取RGB值。
现在我试图从下面的Color Wheel图像中获取RGB,而不使用canvas getImageData。
如果没有画布,我怎么能这样做?
使用画布可以运行。
$('#picker').click(function(e) { // mouse move handler
// get coordinates of current position
var canvasOffset = $(canvas).offset();
var canvasX = Math.floor(e.pageX - canvasOffset.left);
var canvasY = Math.floor(e.pageY - canvasOffset.top);
alert("canvasX " + canvasX + " canvasY " + canvasY);
// get current pixel
var imageData = ctx.getImageData(canvasX, canvasY, 1, 1);
var pixel = imageData.data;
alert(JSON.stringify(pixel));
});
我不能使用canvas只有这个javascript任何人都可以告诉我从图像中获取getImageData的最佳方法我需要构建一个带有for循环的rgb网格,并从x和y值中计算出所选像素然后匹配它。
真的难以在哪里开始任何帮助?
答案 0 :(得分:0)
这是@Pointy的好主意:
只用一个色轮楔子来说明。您可以展开此起点以包含色轮中的所有楔形。
示例代码和演示:http://jsfiddle.net/m1erickson/9pc4orw8/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
#wheel{border:1px solid red;}
#results{width:50px;height:25px;background-color:black;border:1px solid green;}
</style>
<script>
$(function(){
var $wheel=$("#wheel");
var wheelOffset=$wheel.offset();
var offsetX=wheelOffset.left;
var offsetY=wheelOffset.top;
var PI=Math.PI;
var cx=0;
var cy=0;
// define the angle & radius of each color in the color wheel
var colors=[];
colors.push({sAngle:0,eAngle:PI/6,sRadius:0,eRadius:15,color:'rgb(255,255,255)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:15,eRadius:32,color:'rgb(253,237,238)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:32,eRadius:53,color:'rgb(251,211,212)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:53,eRadius:87,color:'rgb(246,145,149)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:87,eRadius:117,color:'rgb(240,73,80)'});
colors.push({sAngle:0,eAngle:PI/6,sRadius:117,eRadius:138,color:'rgb(237,27,36)'});
$("#wheel").mousedown(function(e){handleMouseDown(e);});
// test the current mouse position against the saved angle & radius of each color
// return the colors index of any color under the mouse
function hit(mx,my){
var hitIndex=-1;
for(var i=0;i<colors.length;i++){
var c=colors[i];
var a0=c.sAngle;
var a1=c.eAngle;
var r0=c.sRadius;
var r1=c.eRadius;
var dx=mx-cx;
var dy=my-cy;
var radius=Math.sqrt(dx*dx+dy*dy);
var angle=Math.atan2(dy,dx);
if(angle>a0 && angle<a1 && radius>r0 && radius<r1){
hitIndex=i;
break;
}
}
return(hitIndex);
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
var colorIndex=hit(mx,my);
if(colorIndex>=0){
$('#results').css('background-color',colors[colorIndex].color);
}
}
}); // end $(function(){});
</script>
</head>
<body>
Click to select color:<div id=results></div>
<img id=wheel src='https://dl.dropboxusercontent.com/u/139992952/multple/colorwheel1.png'/>
</body>
</html>