我正在研究此画布绘图,并希望添加新的绘图效果。如您所见,绘图从curPoint
开始并在curPoint
结束,但是有什么方法可以从curPoint
开始并从一边到另一边向下绘制?
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>
最佳答案
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>