Reputation: 6316
I am working on this canvas drawing, and wish to add a new effect of drawing. As you can see the drawing starts from curPoint
and end at curPoint
but is there any way to start from curPoint
and draw from to side to down?
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>
Upvotes: 0
Views: 112
Reputation: 1271
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>
Upvotes: 1