天天看點

圖檔拾色器

如果要擷取這張圖檔的所有顔色: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>

結果展示:

圖檔拾色器

*如果圖檔不是同域下的,會報跨域錯誤,暫時沒有沒有找到解決辦法。