我试图通过三角形制作旋转图形(画布) 鼠标移动事件 - 结果不是必需的。告诉我在哪里 错误。
calculateAngle(e) {
if (!e) return;
let rect = canvas.getBoundingClientRect(),
vx = e.clientX - this.startX,
vy = e.clientY - this.startY;
this.angle = Math.atan2(vy, vx);
}
binding() {
const self = this;
window.addEventListener('mousemove', (e) => {
self.calculateAngle(e);
});
}
render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(this.startX, this.startY);
ctx.rotate(this.angle * (Math.PI / 180));
ctx.translate(-this.startX, -this.startY);
ctx.beginPath();
ctx.moveTo(this.startX, this.startY);
ctx.lineTo(this.startX + this.width / 2, this.startY + this.height);
ctx.lineTo(this.startX - this.width / 2, this.startY + this.height);
ctx.closePath();
ctx.stroke();
}
}
答案 0 :(得分:0)
Math.atan2
以弧度为单位返回角度。错误在渲染函数中,您将旋转转换为弧度。您不需要执行此操作,因为Math.atan2
的返回已经是弧度。
渲染功能也可以改进为
render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(1,0,0,1,this.startX, this.startY); // set location of origin
// this is where everything
// is rotated around
/*===================================================
your code was incorrect
ctx.rotate(this.angle * (Math.PI / 180));
=====================================================*/
// should be
ctx.rotate(this.angle);
ctx.beginPath();
ctx.lineTo(0, 0);
ctx.lineTo( this.width / 2, this.height);
ctx.lineTo(-this.width / 2, this.height);
ctx.closePath();
ctx.stroke();
ctx.setTransform(1,0,0,1,0,0); // restore default transform
}