我有一个图像和一个输入范围滑块,当我滑动滑块时,我需要根据图像上的颜色更改主体的背景。是可以在javascript中执行此操作还是我们需要采用其他方法?这是我的形象。当我将滑块移动到最左边时,我需要背景为黄色,就像在图像中一样,当我将它移动到最右边时,它应该是绿色
答案 0 :(得分:0)
function getPixelForImage(img){
if(!img.getPixel){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
width, height;
function update(){
canvas.width = width = img.naturalWidth;
canvas.height = height = img.naturalHeight;
(width || height) && ctx.drawImage(img, 0, 0);
}
img.addEventListener('load', update);
update();
Object.defineProperty(img, "getPixel", {
value: function(x, y){
if(x<0 || y<0 || x >= width || y >= height) return 0;
var p = ctx.getImageData(x,y,1,1);
//rgba-color-string
return "rgba(" + p[0] + ", " + p[1] + ", " + p[2] + ", " + (p[3]/255) + ")";
//uin32 argb-value to calc with
//return p[3]<<24 | p[0]<<16 | p[1]<<8 | p[2];
}
});
}
return img;
}
getPixelForImage(someImage).getPixel(10, 10);
//or
getPixelForImage(someImage);
//...
someImage.getPixel(x, y);
//...
但您可能会遇到CORS问题