SVG.js: 为什么旋转的行为很奇怪

SVG.js: why does rotate behave in a weird way

我正试图让一辆带有罗盘的公共汽车沿线移动。但是,我无法让指南针正常旋转,它以一种非常奇怪的方式旋转和移动。

你能帮我找出问题所在吗?

这里是link到Fiddle:https://jsfiddle.net/ugvapdrj(我还没有修复CSS所以它向右溢出。)

谢谢!

代码:

<div id="drawing"></div>
let canvas = SVG('drawing').size(2000, 2000)
let compassSize = 42;
let lineColour = '#f00';


let Rsc2muVkt = canvas
  .path(
    'M736 96V72c0-13-11-24-24-24h-75c-18 0-35 7-48 18l-104 94c-23 21-54 32-85 32H0'
  )
  .stroke({
    color: lineColour
  })
  .fill('none');

// Buses
let bus = canvas.image(
  'https://s3-ap-southeast-1.amazonaws.com/viabus-develop-media-resource-ap-southeast/Vehicle+Images/entity/mu/veh_core_mu_06.png',
  compassSize
);
let busCompass = canvas.image(
  'https://s3-ap-southeast-1.amazonaws.com/viabus-develop-media-resource-ap-southeast/Network+Images/Azimuth/Public/veh_ring_white.png',
  compassSize
);

moveBus(bus, busCompass, Rsc2muVkt, 0);


for (let i = 0; i <= 100; i++) {
  setTimeout(() => {
    moveBus(bus, busCompass, Rsc2muVkt, i);
  }, 1000 + i * 200);
}

function moveBus(bus, busCompass, path, to) {
  const p = path.pointAt(to / 100 * path.length());
  const newPosition = {
    x: p.x,
    y: p.y
  };

  const oldX = bus.cx();
  const oldY = bus.cy();

  bus.center(newPosition.x, newPosition.y);
  busCompass.center(newPosition.x, newPosition.y);

  const newX = bus.cx();
  const newY = bus.cy();

  const dx = newX - oldX;
  const dy = newY - oldY;
  const rotatingAngle = Math.atan2(dy, dx) * 180 / Math.PI;

  busCompass.rotate(rotatingAngle + 90);
}

当您尝试将指南针置于下一帧动画的中心时,指南针仍在旋转。这会导致 busCompass.center(...) 调用使用旋转坐标系。

您应该先调用 busCompass.rotate(0); 重置旋转,然后 busCompass.center(...) 将按预期工作,最后的旋转将完成。