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

时间:2019-04-16 12:29:03

标签: javascript html svg svg.js

我正在尝试乘坐指南针沿直线行驶的公共汽车。但是,我无法使指南针正确旋转,它以一种非常奇怪的方式旋转并移动。

能不能帮我找出问题所在?

以下是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);
}

1 个答案:

答案 0 :(得分:1)

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

您应该先致电busCompass.rotate(0);重置轮播,然后busCompass.center(...)将按预期工作,并且最后的轮换将完成。