大概就是这样的思路:
- 读取画布数据,使用 CanvasRenderingContext2D.getImageData接口;
- 遍历画布数据,并将通过范围检测的颜色改成目标颜色,这里唯一的难度就是这个范围检测函数;
- 把改完的
imageData
重新画到画布上去。
检测函数可以是长这样:
/**
* @method colorDetect - 检测颜色是否在指定的范围内
*
* @param { Uint8ClampedArray } color - 待检测的颜色
* @param { Uint8ClampedArray } centerColor - 用户指定的标准色
* @param { Uint8ClampedArray } range - 由用户选定的取色范围计算而来
*
* @returns {boolean}
*/
const colorDetect = (color, centerColor, range) => {
const centerR = (3 << 6) & centerColor
const centerG = (3 << 4) & centerColor
const centerB = (3 << 2) & centerColor
const centerA = 3 & centerColor
const colorR = (3 << 6) & color
const colorG = (3 << 4) & color
const colorB = (3 << 2) & color
const colorA = 3 & color
const rangeR = (3 << 6) & range
const rangeG = (3 << 4) & range
const rangeB = (3 << 2) & range
const rangeA = 3 & range
if (colorR < centerR - range || colorR > centerR + rangeR) {
return false
}
if (colorG < centerG - range || colorG > centerG + rangeG) {
return false
}
if (colorB < centerB - range || colorB > centerB + rangeB) {
return false
}
if (colorA < centerA - range || colorA > centerA + rangeA) {
return false
}
return true
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…