鼠标运动事件中三角形的旋转图(画布)



我尝试通过三角形将旋转图(画布(在鼠标运动事件 - 结果尚未按需要。告诉我哪里错误。

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();
    }
}

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
}

最新更新