图片拾色器

本文介绍了一个基于canvas的图片拾色器实现方法。通过引入特定插件,可以获取图片上任意点的颜色信息,包括RGB、RGBA和十六进制颜色值。然而,该方法在IE8等低版本浏览器中不支持,且在Chrome本地环境中可能因canvas跨域问题导致无法正常工作,建议在服务器环境下测试。
摘要由CSDN通过智能技术生成

如果要获取这张图片的所有颜色:https://segmentfault.com/a/1190000009345753   预览效果:

http://jsrun.net/DjkKp/edit


使用的插件来自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>


结果展示:


*如果图片不是同域下的,会报跨域错误,暂时没有没有找到解决办法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值