计算交点的坐标

时间:2014-11-07 13:15:41

标签: javascript canvas intersection

我有两条线,我想计算它们的交点。 见http://jsfiddle.net/magglomag/7sydgkt6/1/

红线坐标

P1 ( 150, 0 )

P2 ( 125, (stepsY+150)/2 )

蓝线坐标

Q1 ( 150, 150 )

Q2 ( 125, (stepsY)/2 )

-

我发现你必须为每一行推导出像f(x) = m*x + n这样的线性函数来计算交集。

-

第1步

获得斜率m:

m = (y2 - y1) / (x2 - x1)

红线斜率

mP = - ( (stepsY + 150) / 50 )

蓝线斜率

mQ = - ( ((stepsY/2) - 150) / 25 )

-

第2步

第二步是定义y-intersect n:

红线y-intersect

nP = ( (stepsY + 150) / 50 ) * 150

蓝线y-intersect

nQ = ( ( (stepsY/2) - 150) / 25 ) * 150 ) - 150

-

第3步

现在我可以推导出这些功能:

红线功能

f(x) = mP * x + nP

f(x) = ( - ( (stepsY + 150) / 50 ) * x) + ( (stepsY + 150) / 50 ) * 150

蓝线功能

f(x) = mQ * x + nQ

f(x) = ( - ( ( (stepsY/2) - 150) / 25 ) * x) + ( ( (stepsY/2) - 150) / 25 ) * 150 ) - 150

-

第4步

现在我需要你的帮助! 下一步是将mP * x + nP = mQ * x + nQ这两个函数都等同,但是我没有得到它。 如果有人可以帮忙的话会很棒!

-

JS

var mouseX  = 0;
var mouseY  = 0;

var stepsY  = 75;
var stepsX  = 100;

var pageY = 0;
var pageX = 0;

$(window).on({
    load: resizeCanvas()
});


function resizeCanvas() {
    document.onmousemove = function(e) { 
        mouseX = e.pageX;
        mouseY = e.pageY;
    }
}


var loop = setInterval(function() {

    var canvas = document.getElementById('canvas');

    if (canvas.getContext) {

        stepsY += ( ( 125 + parseInt(-mouseY / ($(document).height() / 85 ) )) - stepsY ) / 12;
        stepsX += ( ( 125 + parseInt(-mouseX / ($(document).width() / 46 ) )) - stepsX ) / 12;

        var ctx = canvas.getContext('2d');

        if ( window.devicePixelRatio >= 2 ) {
            canvas.width = 600;
            canvas.height = 300;
            canvas.style.width = "300px";
            canvas.style.height = "150px";
            ctx.scale(2,2);
        } else {
            canvas.style.width = "300px";
            canvas.style.height = "150px";
        }

        ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);

        ctx.beginPath();
        ctx.moveTo( 150, 0 );
        ctx.lineTo( 125, (stepsY+150)/2 );
        ctx.strokeStyle = "red";
        ctx.stroke();        

        ctx.beginPath();
        ctx.moveTo( 150, 150 );
        ctx.lineTo( 125, (stepsY)/2 );
        ctx.strokeStyle = "blue";
        ctx.stroke();   

    }    

}, 20);

1 个答案:

答案 0 :(得分:1)

因此,将等式设为等于

mP*x + nP = mQ*x + nQ

然后解决x得到

mP*x - mQ*x = nQ - nP
(mP - mQ)x = nQ - nP

x = (nQ - nP)/(mP - mQ)       

(如果(mP - mQ)= 0那么线是平行的并且没有交点) 并且y坐标是

y = mP * x + nP     or     y = mQ * x + nQ

这两个方程应该产生相同的y值(直到舍入误差)。