在画布旋转后查找坐标

Ery*_*cik 2 javascript html5 canvas html5-canvas

0到0,-70由此:

ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.rotate(Math.PI/-10;);
ctx.beginPath();
ctx.moveTo(0,0); 
ctx.lineTo(0,-70);
ctx.stroke();
Run Code Online (Sandbox Code Playgroud)

我可以通过'PI/-10'旋转它,这是有效的.

如何在使用旋转后获得x,y点数?

小智 8

您的x和y点仍然是0和-70,因为它们相对于平移(旋转).它基本上意味着您需要"反向工程"矩阵以获得您在画布上看到的结果位置.

如果你想计算一个在-10度处变成70像素的线,你可以使用简单的三角学来自己计算它(这比在矩阵中向后排序更容易).

你可以使用这样的函数来获取你的上下文,线的起始位置(x,y)你要绘制的线的长度(以像素为单位)和角度(以度为单位).它画线,并用返回一个对象xy该行的终点:

function lineToAngle(ctx, x1, y1, length, angle) {

    angle *= Math.PI / 180;

    var x2 = x1 + length * Math.cos(angle),
        y2 = y1 + length * Math.sin(angle);

    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();

    return {x: x2, y: y2};
}
Run Code Online (Sandbox Code Playgroud)

然后将其称为:

var pos = lineToAngle(ctx, 0, 0, 70, -10);

//show result of end point
console.log('x:', pos.x.toFixed(2), 'y:', pos.y.toFixed(2));
Run Code Online (Sandbox Code Playgroud)

结果:

x: 68.94 y: -12.16
Run Code Online (Sandbox Code Playgroud)

或者你可以通过这样做来扩展画布的上下文:

if (typeof CanvasRenderingContext2D !== 'undefined') {

    CanvasRenderingContext2D.prototype.lineToAngle = 
        function(x1, y1, length, angle) {

            angle *= Math.PI / 180;

            var x2 = x1 + length * Math.cos(angle),
                y2 = y1 + length * Math.sin(angle);

            this.moveTo(x1, y1);
            this.lineTo(x2, y2);

            return {x: x2, y: y2};
        }
}
Run Code Online (Sandbox Code Playgroud)

然后直接在您的上下文中使用它,如下所示:

var pos = ctx.lineToAngle(100, 100, 70, -10);
ctx.stroke(); //we stroke separately to allow this being used in a path

console.log('x:', pos.x.toFixed(2), 'y:', pos.y.toFixed(2));
Run Code Online (Sandbox Code Playgroud)

(0度将指向右侧).