cesium中,获取光标处颜色
替换官方的helloworld.html即可
<!doctype html>
<html lang="en">
<head>
<!-- Use correct character set. -->
<meta charset="utf-8" />
<!-- Tell IE to use the latest, best version. -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
/>
<title>Hello World!</title>
<script src="../Build/CesiumUnminified/Cesium.js"></script>
<style>
@import url(../Build/CesiumUnminified/Widgets/widgets.css);
html,
body,
#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
const viewer = new Cesium.Viewer("cesiumContainer", {
contextOptions: { webgl: { preserveDrawingBuffer: true } }, // 关键配置
});
const scene = viewer.scene;
let mousePosition = null;
const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction((movement) => {
mousePosition = movement.endPosition;
test();
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
function test() {
// 精确坐标系转换
const x = Math.floor(mousePosition.x);
const y = Math.floor(scene.canvas.height - mousePosition.y);
if (
x < 0 ||
x >= scene.canvas.width ||
y < 0 ||
y >= scene.canvas.height
)
return;
// 新版核心修正:直接使用WebGL常量
const gl = scene.context._gl;
const pixel = new Uint8Array(4);
gl.readPixels(
x,
y,
1,
1,
gl.RGBA, // 对应格式常量
gl.UNSIGNED_BYTE, // 对应类型常量
pixel,
);
// 空值保护
if (!pixel || pixel.length < 4) return;
const color = Cesium.Color.fromBytes(
pixel[0],
pixel[1],
pixel[2],
pixel[3],
);
console.log(
"%c" + `RGBA: [${pixel.join(", ")}]`,
`background-color: ${color.toCssHexString()}`,
);
}
</script>
</body>
</html>