选用zoomTo函数是为了不锁定视角,且可以异步加载
参考:Cesium中的lookAt/lookAtTransform/setView/zoomTo_cesium lookat-CSDN博客
这个代码是一个过渡动画,如果只想固定视角,把循环去掉使用固定的参数就可以
// 起始方位角(当前视角水平方向角度,这里示例设为0度,转换为弧度)
var startingHeading = Cesium.Math.toRadians(0);
// 起始俯仰角(当前视角垂直方向角度,转换为弧度)
var startingPitch = Cesium.Math.toRadians(-60);
// 目标方位角(想要缓慢移动到的水平方向角度,转换为弧度)
var targetHeading = Cesium.Math.toRadians(230);
// 目标俯仰角(想要缓慢移动到的垂直方向角度,转换为弧度)
var targetPitch = Cesium.Math.toRadians(-15);
//过渡时的高度
var startingRange = 5000;
//最终高度
var targetRange = 1000;
// 过渡时长,单位毫秒,这里设为5000毫秒(即5秒)
var duration = 10000;
// 获取当前时间戳,用于记录开始过渡的时间
var startTime = Date.now();
//初始过渡动画
function updateCamera() {
var currentTime = Date.now();
var elapsedTime = currentTime - startTime;
if (elapsedTime < duration) {
// 计算方位角改变的速率(每一毫秒改变的弧度值)
var headingRate = (targetHeading - startingHeading) / duration;
// 计算俯仰角改变的速率(每一毫秒改变的弧度值)
var pitchRate = (targetPitch - startingPitch) / duration;
// 计算高度改变的速率
var rangeRate = (targetRange - startingRange) / duration;
// 更新当前方位角
var currentHeading = startingHeading + headingRate * elapsedTime;
// 更新当前俯仰角
var currentPitch = startingPitch + pitchRate * elapsedTime;
// 更新当前高度
var currentRange = startingRange + rangeRate * elapsedTime;
var orientation = new Cesium.HeadingPitchRange(currentHeading, currentPitch, currentRange);
viewer.zoomTo(tileset, orientation);
// 使用requestAnimationFrame继续下一帧更新,实现平滑过渡效果
Cesium.requestAnimationFrame(updateCamera);
} else {
// 过渡完成后,直接设置为目标角度,确保精准达到目标位置
var finalOrientation = new Cesium.HeadingPitchRange(targetHeading, targetPitch, targetRange);
viewer.zoomTo(tileset, finalOrientation);
}
}
// 启动视角缓慢移动的函数
updateCamera();
封装函数版本
javascript
//初始过渡动画
function updateCamera(startTime, startingHeading, targetHeading, startingPitch, targetPitch, startingRange, targetRange, duration) {
let currentTime = Date.now();
let elapsedTime = currentTime - startTime;
if (elapsedTime < duration) {
// 计算方位角改变的速率(每一毫秒改变的弧度值)
let headingRate = (targetHeading - startingHeading) / duration;
// 计算俯仰角改变的速率(每一毫秒改变的弧度值)
let pitchRate = (targetPitch - startingPitch) / duration;
// 计算高度改变的速率
let rangeRate = (targetRange - startingRange) / duration;
// 更新当前方位角
let currentHeading = startingHeading + headingRate * elapsedTime;
// 更新当前俯仰角
let currentPitch = startingPitch + pitchRate * elapsedTime;
// 更新当前高度
let currentRange = startingRange + rangeRate * elapsedTime;
let orientation = new Cesium.HeadingPitchRange(currentHeading, currentPitch, currentRange);
viewer.zoomTo(tileset, orientation);
// 使用requestAnimationFrame继续下一帧更新,实现平滑过渡效果
Cesium.requestAnimationFrame(function (time) {
updateCamera(startTime, startingHeading, targetHeading, startingPitch, targetPitch, startingRange, targetRange, duration);
});
} else {
// 过渡完成后,直接设置为目标角度,确保精准达到目标位置
let finalOrientation = new Cesium.HeadingPitchRange(targetHeading, targetPitch, targetRange);
viewer.zoomTo(tileset, finalOrientation);
}
}