2017-12-27 12 views
0

このキャンバスの描画を見て、新しい描画効果を追加できるかどうか教えてください。ご覧のとおり、図面はcurPointから始まり、curPointで終了しますが、curPointから始まり、下から上に向かっていく方法はありますか?キャンバスに長方形を描く両側に真ん中のサイドから

enter image description here

var canvas = document.getElementById("canvasWindow"); 
 
    var c = canvas.getContext("2d"); 
 
    var curPoint = { 
 
     x : 300, 
 
     y : 100, 
 
     index : 0 
 
    } 
 
    var points = [{x:100, y:100}, {x:100, y:300}, {x:500, y:300}, {x:500, y:100}, {x:300, y:100}]; 
 
    function toPoints(points){ 
 
     var targetPoint = points[curPoint.index]; 
 
     var tx = targetPoint.x - curPoint.x, 
 
      ty = targetPoint.y - curPoint.y 
 
     var dist = Math.sqrt(tx*tx+ty*ty), 
 
      rad = Math.atan2(ty,tx); 
 
     var velX = (tx/dist)*1; 
 
     var velY = (ty/dist)*1; 
 
     curPoint.x += velX; 
 
     curPoint.y += velY; 
 
     if(dist < 2){ 
 
      curPoint.index++; 
 
     } 
 
     c.fillRect(curPoint.x, curPoint.y, 1, 1); 
 
     if(curPoint.index < points.length){ 
 
      setTimeout(function(){toPoints(points)}, 5); 
 
     } 
 
    } 
 
    toPoints(points);
<canvas id="canvasWindow" width="600" height="600"></canvas>

+0

ただ、同時に2つのパスを描画します。 – destoryer

答えて

1

var canvas = document.getElementById("canvasWindow"); 
 
var c = canvas.getContext("2d"); 
 
var curPoint1 = { 
 
    x : 301, 
 
    y : 100, 
 
    index : 0 
 
}; 
 
var curPoint2 = { 
 
    x : 299, 
 
    y : 100, 
 
    index : 0 
 
}; 
 

 
var points1 = [{x:100, y:100}, {x:100, y:300}, {x:300, y:300}]; 
 
var points2 = [{x:500, y:100}, {x:500, y:300}, {x:300, y:300}]; 
 

 
function toPoints(points, curPoint){ 
 
    var targetPoint = points[curPoint.index]; 
 
    var tx = targetPoint.x - curPoint.x, 
 
     ty = targetPoint.y - curPoint.y 
 
    var dist = Math.sqrt(tx*tx+ty*ty); 
 
    var velX = (tx/dist)*1; 
 
    var velY = (ty/dist)*1; 
 
    curPoint.x += velX; 
 
    curPoint.y += velY; 
 
    if(dist <= 1){ 
 
     curPoint.index++; 
 
    } 
 
    c.fillRect(curPoint.x, curPoint.y, 1, 1); 
 
    if(curPoint.index < points.length){ 
 
     setTimeout(function(){toPoints(points, curPoint)}, 2); 
 
    } 
 
} 
 
toPoints(points1, curPoint1); 
 
toPoints(points2, curPoint2);
<canvas id="canvasWindow" width="600" height="600"></canvas>

関連する問題