【问题标题】:HTML5 canvas. Draw a line and make it shorterHTML5 画布。画一条线,让它更短
【发布时间】:2014-05-16 09:36:33
【问题描述】:

我有一个 HTML5 画布,左上角有 0,0。

我从 10,15 到 100,300 画一条线。

保持相同的斜率...如果我想要那条线,那么 2 个末端坐标是多少 每端短 10 个单位?

【问题讨论】:

    标签: html canvas grid coordinates cartesian-coordinates


    【解决方案1】:

    执行此操作的步骤是:
    1) 获取线的单位向量。
    (这是一个长度为 1 的向量,与您的线具有相同的方向。)
    2) 在起点/终点添加/减去所需长度 * 单位向量。
    3)...画线!

    小提琴: http://jsbin.com/vajasibe/1/edit?js,output

    第 1 步,使用就地功能:

    function buildUnitVector(p1, p2, uVect) {
         uVect.x = (p2.x - p1.x);
         uVect.y = (p2.y - p1.y );
         var vectorNorm = Math.sqrt( sq(uVect.x)+sq(uVect.y) );
         uVect.x/=vectorNorm;
         uVect.y/=vectorNorm;
    }
    

     function sq(x) { return x*x ;}
    

    第2步,现场也:

    function drawShorterLine(ctx, p1, p2, a, b) {
        buildUnitVector(p1, p2, unitVector);
        sp1.x = p1.x + unitVector.x * a;
        sp1.y = p1.y + unitVector.y * a;
        sp2.x = p2.x - unitVector.x * b;
        sp2.y = p2.y - unitVector.y * b;
        ctx.beginPath();
        ctx.moveTo(sp1.x, sp1.y);
        ctx.lineTo(sp2.x, sp2.y);
        ctx.stroke();
    }
    var unitVector = { x:0, y:0 }, sp1 = {x:0,y:0},
                sp2 = {x:0, y:0 } ; 
    
     // use with
     var p1 = {x:0, y:0}, p2 = {x:100, y:300} ;
     drawShorterLine(ctx, p1, p2, 10, 10);
    

    【讨论】:

      猜你喜欢
      • 2012-05-30
      • 2014-07-19
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      相关资源
      最近更新 更多