画布旋转后查找坐标 [英] Finding coordinates after canvas Rotation

查看:22
本文介绍了画布旋转后查找坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

0 到 0,-70 通过这个:

0 to 0,-70 by this :

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

我可以将其旋转PI/-10",这样就可以了.

And I can rotate that by 'PI/-10', and that works.

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

How i can get the x,y points of this after using rotate?

推荐答案

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

Your x and y points will still be 0 and -70 as they are relative to the translation (rotation). It basically means you would need to "reverse engineer" the matrix to get the resulting position you see on the canvas.

如果您想计算一条在 -10 度处延伸 70 像素的线,您可以使用简单的三角函数自行计算(这比在矩阵中倒退更容易).

If you want to calculate a line which goes 70 pixels at -10 degrees you can use simple trigonometry to calculate it yourself instead (which is easier than going sort of backwards in the matrix).

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

You can use a function like this that takes your context, the start position of the line (x, y) the length (in pixels) and angle (in degrees) of the line you want to draw. It draw the line and returns an object with x and y for the end point of that line:

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

那么就叫它:

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

结果:

x: 68.94 y: -12.16

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

Or you can instead extend the canvas' context by doing this:

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

然后像这样直接在你的上下文中使用它:

And then use it directly on your context like this:

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

(0 度将指向右侧).

(0 degrees will point to the right).

这篇关于画布旋转后查找坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆