Cartesian2是 CesiumJS 中的一个类,表示在二维笛卡尔坐标系中的点,它由两个坐标值表示。一般来说,第一个坐标代表水平方向的距离,第二个坐标代表垂直方向的距离。在 CesiumJS 中,Cartesian2 用于描述点的位置、矢量、大小等属性,常常作为其它对象的属性被使用到。
new Cartesian2(x, y)
x: Number 类型,点的水平坐标值。y: Number 类型,点的垂直坐标值。使用该构造函数可以得到一个 Cartesian2 类型的实例,例如:
const point = new Cesium.Cartesian2(10, 20);
这将得到一个 x 坐标值为 10,y 坐标值为 20 的点。
x: Number 类型,表示点在水平方向上的距离值。y: Number 类型,表示点在垂直方向上的距离值。完整的代码示例:
// 创建一个 Cartesian2 对象
const point = new Cesium.Cartesian2(10, 20);
// 读取其属性值
console.log(point.x); // 输出 10
console.log(point.y); // 输出 20
clone(result)克隆当前点实例,返回其一个副本。可选参数 result 用于传递输出结果的实例对象。
const point = new Cesium.Cartesian2(10, 20);
const clone = point.clone();
distance(other)计算当前点实例到另一个点 other 的距离值。
const point1 = new Cesium.Cartesian2(10, 20);
const point2 = new Cesium.Cartesian2(30, 40);
const distance = point1.distance(point2);
equals(other, relativeEpsilon)比较当前点实例和另一个点 other 是否相等。
const point1 = new Cesium.Cartesian2(10, 20);
const point2 = new Cesium.Cartesian2(10, 20);
const point3 = new Cesium.Cartesian2(20, 30);
const equals1 = point1.equals(point2); // 输出 true
const equals2 = point1.equals(point3); // 输出 false
toString()得到当前点实例的文本描述,一般是 "(x, y)" 这样的格式。
const point = new Cesium.Cartesian2(10, 20);
const str = point.toString(); // 输出 "(10, 20)"
以下是一个使用 Cartesian2 对象的例子。在这个例子中,用 Cartesian2 描述了三个点的位置,用线条连接了这些点。
const viewer = new Cesium.Viewer("cesiumContainer");
// 使用 Cartesian2 描述点的位置
const point1 = new Cesium.Cartesian2(-1000000.0, 0.0);
const point2 = new Cesium.Cartesian2(0.0, 1000000.0);
const point3 = new Cesium.Cartesian2(1000000.0, 0.0);
// 在 viewer 中绘制线段
viewer.entities.add({
polyline: {
positions: Cesium.Cartesian2.fromArray([point1.x, point1.y, point2.x, point2.y, point3.x, point3.y]),
width: 2,
material: new Cesium.ColorMaterialProperty(Cesium.Color.RED),
},
});