我试图在x / y平面上给出三个点,以方形图案创建x / y坐标网格。 A grid like this
这用于驱动gcode生成器,用于将工具头移动到3d打印机上所需的x,y位置。我需要考虑正方形的偏斜和偏离,因此正方形内的x / y点网格需要考虑对齐。
function genGrid (topLeft, btmRight, btmLeft, rows, cols) {
// Generate Grid
// Return array of coordinates like the red dots in the picture I made.
}
[此图片有助于更好地解释!]
答案 0 :(得分:0)
这段代码就行了!
<script>
function grid(p1, p2, count) {
pointPerRow = Math.sqrt(count);
p3 = {
x: (p1.x + p2.x + p2.y - p1.y) / 2,
y: (p1.y + p2.y + p1.x - p2.x) / 2
};
p4 = {
x: (p1.x + p2.x + p1.y - p2.y) / 2,
y: (p1.y + p2.y + p2.x - p1.x) / 2
};
edgeLenght = Math.sqrt( (p3.x - p1.x)**2 + (p3.y - p1.y)**2);
vectorH = {
x: (p3.x - p1.x) / edgeLenght,
y: (p3.y - p1.y) / edgeLenght
};
vectorV = {
x: (p4.x - p1.x) / edgeLenght,
y: (p4.y - p1.y) / edgeLenght
};
movingStep = edgeLenght / (pointPerRow -1);
result = {};
for (var i = 0; i < pointPerRow; i++) {
row = {};
point = {
x: p1.x + vectorH.x * movingStep * (i),
y: p1.y + vectorH.y * movingStep * (i),
}
for (var j = 0; j < pointPerRow; j++) {
row[j] = {
x: point.x + vectorV.x * movingStep * (j),
y: point.y + vectorV.y * movingStep * (j),
};
}
result[i] = row;
}
// Debugging
for (var x=0;x < pointPerRow; x++) {
for (var y=0; y < pointPerRow; y++) {
ctx.fillStyle="#000000";
ctx.fillRect(result[x][y].x,result[x][y].y,10,10);
}
}
ctx.fillStyle="#FF0000";
ctx.fillRect(p1.x,p1.y,5,5);
ctx.fillRect(p2.x,p2.y,5,5);
ctx.fillRect(p3.x,p3.y,5,5);
ctx.fillRect(p4.x,p4.y,5,5);
return result;
}
// Create a canvas that extends the entire screen
// and it will draw right over the other html elements, like buttons, etc
var canvas = document.createElement("canvas");
canvas.setAttribute("width", window.innerWidth);
canvas.setAttribute("height", window.innerHeight);
canvas.setAttribute("style", "position: absolute; x:0; y:0;");
document.body.appendChild(canvas);
//Then you can draw a point at (10,10) like this:
var ctx = canvas.getContext("2d");
var grid = grid({x:100, y:50}, {x:200, y:350}, 16);
</script>