圖片顏色吸管工具
上傳圖片並點擊圖片中的任何區域來採集顏色:
十六進位代碼: #000000
RGB值: RGB(0,0,0)
上傳圖片並點擊圖片中的任何區域來採集顏色:
十六進位代碼: #000000
RGB值: RGB(0,0,0)
透過該工具可以用來確定網站主色調、設計海報、設計網頁等。
本工具主要由以下幾個部分組成:
用戶透過 <input type="file">
選擇圖片後,利用JavaScript 文件讀取器
API 讀取圖片數據,並將其繪製到 <canvas>
畫布上。
colorPickerImageUploader.addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
img.onload = function() {
// 计算图片缩放比例,最大宽度 800px,保持比例
const maxWidth = 800;
const scale = img.width > maxWidth ? maxWidth / img.width : 1;
const newWidth = img.width * scale;
const newHeight = img.height * scale;
// 设置画布大小与图片一致
colorPickerCanvas.width = newWidth;
colorPickerCanvas.height = newHeight;
// 在画布上绘制图片
ctx.drawImage(img, 0, 0, newWidth, newHeight);
imageUploaded = true;
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
});
核心邏輯:
影像
對象。800像素
,並保持比例縮放。帆布
畫布的尺寸與調整後的圖片一致。ctx.繪製影像(img, 0, 0,新寬度,新高度);
在 帆布
上繪製圖片。當用戶在 帆布
上點擊時,透過 取得影像資料()
方法取得該像素的顏色值。
colorPickerCanvas.addEventListener('click', function(e) {
if (!imageUploaded) {
alert('请先上传图片');
return;
}
const x = e.offsetX;
const y = e.offsetY;
// 获取该像素的颜色数据
const pixel = ctx.getImageData(x, y, 1, 1).data;
const r = pixel[0];
const g = pixel[1];
const b = pixel[2];
// 计算 Hex 颜色值
const rgb = `rgb(${r}, ${g}, ${b})`;
const hex = rgbToHex(r, g, b);
// 更新 UI
colorPickerBox.style.backgroundColor = hex;
colorPickerHexCode.textContent = hex;
colorPickerRgbValue.textContent = rgb;
});
核心邏輯:
帆布
的 點選
事件,取得滑鼠點擊的座標 x, y
(基於 帆布
)。ctx.取得影像資料(x,y,1,1).數據
取得該點的像素資料(RGBA)。RGB
值,並轉換為 十六進位
值。為了相容於更多顏色格式,需要將 RGB 值轉換成 十六進位 格式:
function rgbToHex(r, g, b) {
return `#${(1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1).toUpperCase()}`;
}
轉換邏輯:
1 << 24
確保24 位元整數空間,r << 16 | g << 8 | b
將 RGB
組合為整數。.toString(16)
轉換為16 進位字串。.slice(1).toUpperCase()
確保顏色值為標準6 位元大寫格式。使用者可以點擊複製按鈕,將顏色值複製到剪貼簿,並在複製後修改按鈕狀態。
colorPickerCopyHexBtn.addEventListener('click', function() {
if (!imageUploaded) return;
const hex = colorPickerHexCode.textContent;
navigator.clipboard.writeText(hex).then(function() {
colorPickerCopyHexBtn.textContent = '已复制';
colorPickerCopyHexBtn.classList.add('copied');
setTimeout(() => {
colorPickerCopyHexBtn.textContent = '复制';
colorPickerCopyHexBtn.classList.remove('copied');
}, 2000);
});
});
核心邏輯:
navigator.clipboard.writeText(十六進位)
複製Hex 顏色值到剪貼簿。當用戶在 帆布
上移動滑鼠時,顯示一個吸管樣式的圖標,並隨著滑鼠移動。
colorPickerCanvas.addEventListener('mousemove', function(e) {
if (!imageUploaded) return;
colorPickerIcon.style.left = `${e.pageX - 15}px`;
colorPickerIcon.style.top = `${e.pageY - 15}px`;
colorPickerIcon.style.display = 'block';
});
colorPickerCanvas.addEventListener('mouseleave', function() {
colorPickerIcon.style.display = 'none';
});
核心邏輯:
滑鼠移動
事件時,調整 顏色選擇器圖標
的 左邊
和 頂部
使其跟隨滑鼠。滑鼠離開
事件時,隱藏吸管圖示。保持圖片比例
最大寬度 = 800
計算縮放比例,防止圖片變形畫布尺寸同步
帆布
大小與圖片尺寸保持一致,確保顏色擷取座標正確。避免跨域問題
帆布
繪製圖片時如果有跨域問題,需確保圖片來源允許 CORS
(本地文件不會有此問題)。滑鼠精準吸取顏色
x, y
計算基於 帆布
座標,而不是 窗戶
或 文件
座標。以上就是圖片色彩擷取工具的實現原理和核心程式碼。