Picking pixel from cesium canvas

Hello, I am trying to determine the color of a pixel at a certain location on the cesium canvas. The result is always the same, [0, 0, 0, 255]. I am using the latest version of chrome and cesium and am using Bing maps.

I will be using this to sample the map imagery under a screen overlay so it can dynamically be colored to contrast the map.

I have created a Github gist that can be copied and pasted into a Cesium Sandcastle.

https://gist.github.com/ZacBrownBand/11c0baa90a8b4e3aa5d7db581734bfe0

Here is the code:

var viewer = new Cesium.Viewer(‘cesiumContainer’);
var pixels = new Uint8Array(4);

… Other stuff …

var gl = viewer.canvas.getContext(‘webgl’);
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
console.log(pixels); // always outputs 0,0,0,255

I have feeling this is not doing what I am expecting it is. This is my first time interacting with webgl.

Thanks

You need to use the same context that Cesium is using. I’m not sure what happens when there is more than one context requested from the same canvas. Try:

var pixels = viewer.scene.context.readPixels({

x : x,

y : y,

width : 1,

height : 1

});

console.log(pixels);

That makes sense, I didn't think of that.

I tried updating my example to:

var viewer = new Cesium.Viewer('cesiumContainer');

function getColor(x, y) {
    var pixels = viewer.scene.context.readPixels({
        x: x,
        y: y,
        width: 1,
        height: 1
    });
    console.log(pixels);
}

Sandcastle.addToolbarButton('Get Color at 200, 200', getColor.bind(null,
200, 200));

I still get 0, 0, 0, 255 always.

I’m not sure why that is happening, but here is a work around:

var viewer = new Cesium.Viewer(‘cesiumContainer’);

var scene = viewer.scene;

var context = scene.context;

var readColor = false;

scene.postRender.addEventListener(function() {

if (readColor) {

readColor = false;

var pixels = context.readPixels({

x : 0,

y : 0,

width : 1,

height : 1

});

console.log(pixels);

}

});

Sandcastle.addToolbarButton(‘Get Color’, function() {

readColor = true;

});

This will make sure that the readPixels happens immediately after the scene is rendered.

Thanks Daniel, that does work! Thats a great place to start from. If I
figure out what the issue is ill follow up with you.