DOMPoint转换旋转未在JavaScript中返回预期结果

问题描述

有人可以确认此DOMPoint的转换正常吗?

let point = new DOMPoint(1,1);
let matrix = new DOMMatrix('rotate(-45deg)');
let transformedPoint = point.matrixTransform(matrix);

console.log(point,transformedPoint);

我们在控制台中得到的结果是:

DOMPoint { x: 1,y: 1,z: 0,w: 1 }
 
DOMPoint { x: 1.4142135381698608,y: 0,w: 1 }

我本来希望transformdPoint具有 x:1 y:0 ,因为(1,1)点的角度为45度。我假设转换基于(0,0)的原点吗?

enter image description here

我们能启发我实际进行转换的方式吗?

解决方法

您的图形反转了,原点在左上角,所以1,1实际上在右下角。

然后,您的点1,1与原点0,0之间的距离为hypot( 1 - 0,1 - 0 ),实际上大约为1.414213...
因此,获得此{ x: 1.4142135381698608,y: 0,z: 0,w: 1 }结果确实是正确的。

也许可视化可以使它更清晰:

黄色是来源0,0。 绿色是初始点1,1。 红色每帧旋转一度。

const point = new DOMPoint(1,1);
const matrix = new DOMMatrix("rotate(-1deg)");
let transformedPoint = point.matrixTransform(matrix);
let angle = 1;

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

const axes = new Path2D( "M150 0L150 150M0 75L300 75" );
ctx.font = "14px sans-serif";
draw();

function draw() {
  transformedPoint = transformedPoint.matrixTransform(matrix);
  angle = (angle + 1) % 360;

  // clear
  ctx.setTransform( 1,1,0 );
  ctx.clearRect( 0,canvas.width,canvas.height );

  ctx.fillText( `angle: -${ angle }`,10,10 );

  ctx.stroke( axes );

  // move to the center of canvas and scale by 20
  ctx.setTransform( 20,20,canvas.width / 2,canvas.height / 2 );
  // origin
  ctx.fillStyle = "yellow";
  ctx.fillRect( 0 - 0.5,0 - 0.5,1 );
  // reference point
  ctx.fillStyle = "green";
  ctx.fillRect( point.x - 0.5,point.y - 0.5,1 );
  // transformed
  ctx.fillStyle = "red";
  ctx.fillRect( transformedPoint.x - 0.5,transformedPoint.y - 0.5,1 );
  
  requestAnimationFrame( draw );
}
<canvas id="canvas"></canvas>