繁体   English   中英

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

[英]rotation figure (canvas) by the triangle on the mouse movement event

我尝试在鼠标移动事件上通过三角形制作旋转图形(画布)-结果尚未达到所需。 告诉我哪里有错误。

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM