如果要获取这张图片的所有颜色:https://segmentfault.com/a/1190000009345753 预览效果:
使用的插件来自http://www.jq22.com/jquery-info5319,说明:不支持IE8等低版本浏览器,Chrome本地预览会出现canvas跨域问题,请换用其它浏览器或在服务器环境下测试。
结构:
<canvas id="canvas" width="400px" height="286px">Sorry, your browser dose not support canvas.</canvas>
<hr />
<div class="info" id="currentColor">点击上面的canvas来查看效果</div>
<div id="cursor"></div>
引入的js内容:
<script src="getcanvaspixelcolor.js" type="text/javascript"></script>
if (typeof HTMLElement == 'undefined'){
var HTMLElement = function(){};
if (window.webkit) document.createElement("iframe"); //fixes safari
HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {};
}
HTMLElement.prototype.getPixelColor = function(x, y){
var thisContext = this.getContext("2d");
var imageData = thisContext.getImageData(x, y, 1, 1);
// 获取该点像素数据
var pixel = imageData.data;
var r = pixel[0];
var g = pixel[1];
var b = pixel[2];
var a = pixel[3] / 255
a = Math.round(a * 100) / 100;
var rHex = r.toString(16);
r < 16 && (rHex = "0" + rHex);
var gHex = g.toString(16);
g < 16 && (gHex = "0" + gHex);
var bHex = b.toString(16);
b < 16 && (bHex = "0" + bHex);
var rgbaColor = "rgba(" + r + "," + g + "," + b + "," + a + ")";
var rgbColor = "rgb(" + r + "," + g + "," + b + ")";
var hexColor = "#" + rHex + gHex + bHex;
return {
rgba : rgbaColor,
rgb : rgbColor,
hex : hexColor,
r : r,
g : g,
b : b,
a : a
};
}
调用的js:
<script type="text/javascript">
var draw = function(img) {
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.shadowBlur = 20;
context.shadowColor = "#000000";
context.drawImage(img, 0, 0);
canvas = $("#canvas");
canvas.click(function (e) {
var canvasOffset = canvas.offset();
var canvasX = Math.floor(e.pageX - canvasOffset.left);
var canvasY = Math.floor(e.pageY - canvasOffset.top);
var colorData = document.getElementById("canvas").getPixelColor(canvasX, canvasY);
// 获取该点像素的数据
console.log(colorData);
var color = colorData.hex;
$("#currentColor").html("当前像素(" + canvasX + "," + canvasY + ")颜色为: " + color);
var cursorX = (e.pageX - 5) + "px";
var cursorY = (e.pageY - 5) + "px";
$("#cursor").stop(true, true).css({
"display" : "inline-block",
"left" : cursorX,
"top" : cursorY
}).fadeOut(2500);
});
}
$(document).ready(function () {
var img = new Image();
img.src = "images/demo.jpg";
$(img).load(function () {
draw(img);
});
});
</script>
结果展示:
*如果图片不是同域下的,会报跨域错误,暂时没有没有找到解决办法。