gpt4 book ai didi

javascript - 在 Canvas 上从边的中间向两个方向绘制一个矩形

转载 作者:行者123 更新时间:2023-12-03 02:48:26 25 4
gpt4 key购买 nike

我正在处理这个 Canvas 绘图,并希望添加新的绘图效果。正如您所看到的,绘图从 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>

最佳答案

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>

关于javascript - 在 Canvas 上从边的中间向两个方向绘制一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com