问题场景:
实现点击管道切换颜色功能。管道未使用style.materialOptions的创建管道方式可以正常切换颜色。但是使用了materialOptions设置颜色方式创建的管道,点击后管道消失不见。具体代码如下:
function addDemoGraphic3(graphicLayer) {
const graphic = new mars3d.graphic.PolylineVolumeEntity({
positions: [
[117.358187, 31.838662, 12.23],
[117.4384, 31.819405, 11.78]
],
style: {
shape: "circle",
radius: 80,
cornerType: Cesium.CornerType.BEVELED,
materialType: mars3d.MaterialType.LineFlow,
materialOptions: {
color: "#1a9850",
image: "img/textures/fence-line.png",
speed: 10,
repeat_x: 6
}
},
attr: { remark: "示例3" }
})
graphic.on(mars3d.EventType.click, function (event) {
event.stopPropagation();
console.log("管道点击事件")
// 切换颜色
console.log("旧颜色:", graphic.style.materialOptions.color)
if (graphic.style.materialOptions.color === "#1a9850") {
graphic.style.materialOptions.color = "#61fa08";
console.log("新颜色:", graphic.style.materialOptions.color)
} else {
console.log("切换颜色:默认颜色")
graphic.style.materialOptions.color = "#1a9850";
}
console.log("新颜色:::", graphic.style.materialOptions)
console.log("坐标:::", graphic.positions)
// 更新管道的样式
graphic.setStyle(graphic.style);
graphicLayer.needUpdate = true;
})
graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
}
点击后管道消失不见的原因是:
正确语法参考:
graphic.setStyle({...graphic.style})
最好的修改方式建议:
graphic.setStyle({ materialOptions: { color :"RED"}})
当前效果:
PolylineVolumeEntity通过materialOptions设置颜色,点击切换颜色。
相关代码:
graphic.on(mars3d.EventType.click, function (event) {
event.stopPropagation();
console.log("管道点击事件")
// 切换颜色
console.log("旧颜色:", graphic.style.materialOptions.color)
let newColor = "#61fa08"
if (graphic.style.materialOptions.color === "#1a9850") {
newColor = "#61fa08";
} else {
newColor = "#1a9850";
}
console.log("新颜色:::", graphic.style.materialOptions)
console.log("坐标:::", graphic.positions)
// 更新管道的样式
graphic.setStyle(
{
materialOptions: {
color: newColor,
image: "img/textures/fence-line.png",
speed: 10,
repeat_x: 6
}
}
);
})
graphicLayer.addGraphic(graphic)