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

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

问题描述

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.

如何在使用rotate后获得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.

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

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)要绘制的线的长度(以像素为单位)和角度(以度为单位)。它绘制线并返回一个对象 x y 作为该线的终点:

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

通过这样做:

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度将指向右侧)。

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

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