如何在着色器之前获得原始像素颜色



我有一个ImageLayer和一个RasterSource,它们使用着色器来操作图像的颜色。

在听地图的pointermove时,我得到了指针下像素的颜色,这是由着色器操纵的颜色。

如何在着色器操作之前获得原始颜色?

const extent = [0, 0, 1024, 968]; // the image extent in pixels.
const projection = new Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent,
});
let staticImage = new Static({ // from 'ol/source/ImageStatic'
attributions: '© <a href="http://xkcd.com/license.html">xkcd</a>',
url: "./assets/map.png",
projection: projection,
imageExtent: extent
});
let imageLayer = new ImageLayer({ // from 'ol/layer/Image'
source: new RasterSource({
sources: [staticImage],
operation: function (pixels, data) {
let p = pixels[0];
let grayscale = (p[0] + p[1] + p[2]) / 3;
p[0] = grayscale;
p[1] = grayscale;
p[2] = grayscale;
return p;
}
})
});
let map; // Map from 'ol'
map.on('pointermove', (evt) => {
let pixel = evt.pixel;
let color = imageLayer.getRenderer().getDataAtPixel(pixel, evt.framestate, 1);
// color is the one manipulated by the shader
});

更多代码在这里:
https://codesandbox.io/s/raster-original-pixel-3mejh9?file=/main.js
注意:由于安全限制,我不得不注释掉着色器代码,它把颜色变成灰色


https://openlayers.org/en/latest/examples/static-image.html

我找到了一个解决方法,通过添加一个无操作的重复RasterLayer。诀窍是在颜色处理图层之后添加图层,但不透明度为0.005(显然是最低的值),所以它被渲染,但你看不到它。然后将灰色的alpha值与原始颜色的RGB值合并:

let noopLayer = new ImageLayer({
opacity: 0.005,
source: new RasterSource({
sources: [
staticImage
],
operation: function (pixels, data) {
let p = pixels[0];
return p;
},
}),
});
const map = new Map({
layers: [
rasterLayer,
noopLayer,
],
target: 'map',
view: new View({
projection: projection,
center: getCenter(extent),
zoom: 2,
maxZoom: 8,
}),
});
map.on('pointermove', (evt) => {
const pixel = evt.pixel;
let grey = rasterLayer.getRenderer().getDataAtPixel(pixel, evt.framestate, 1);
let noop = noopLayer.getRenderer().getDataAtPixel(pixel, evt.framestate, 1);
if (grey != null) {
// [228, 228, 228, 255]
console.log('grey:', grey[0], grey[1], grey[2], grey[3]);
// [255, 255, 170, 3]
console.log('noop:', noop[0], noop[1], noop[2], noop[3]);
// [255, 255, 170, 255]
console.log('original:', noop[0], noop[1], noop[2], grey[3]);
}
});

最新更新