我有一个父矩形,我想在父矩形的右上角添加多达10个或更少的矩形,如图所示
我编写了一个代码来做,但是它没有从父矩形居中对齐
this.addPortsToTheTransponder(3);
addPortsToTheTransponder(noOfPortsToBeDrawn: number) {
for (let i = 1; i <= noOfPortsToBeDrawn; i++) {
this.createPorts(i, noOfPortsToBeDrawn);
}
}
/**
*
* @param i number to create ports
*/
createPorts(i: number, noOfPortsToBeDrawn: number): void {
this.context.clearRect(0, 0, this.width, this.height);
/**
* Size(height & width) of each port is calculated as follows,
* A. transpondser size is divided with number of ports to be drawn
* B. And divide the height and width by number of ports to be drawn
*/
const length = this.sizeOfTransponder.height / noOfPortsToBeDrawn;
const height = 10;
const width = 10;
/**
* x is the total of this.x(where this.x is the x value of first transponder)
* and width of transponder width
*/
const x = this.x + this.sizeOfTransponder.width;
/**
* y is the total of this.y (where this.y is position where all objects drawn)
* and nth of ports * length
*/
const y = this.y + i * length - length / 2;
/**
*
*/
this.context.rect(
x,
y,
height,
width
);
this.context.stroke();
}
我如何对齐始终从中心绘制的小矩形,而与小矩形的总数无关? 这是code
答案 0 :(得分:1)
只涉及一点数学。 假设您的大矩形位于x = 20,y = 20,其宽度为200,高度为300。
现在您要在其右侧绘制5个较小的矩形。
牢记这一点,您知道5个小矩形的最大垂直空间是大矩形的高度-300-因此,我们将300除以5得到60。如果您只是开始每60像素开始绘制一个小矩形,在大矩形的y位置,小矩形将与顶部对齐。这里的技巧是将计算出的60-30-的一半相加,再减去一个小矩形的一半高度,以得到其中心。
这是一个例子-您可以使用变量 numberOfRectangles 来查看它始终位于大矩形边的中心:
var bigRectangle = {
x: 0,
y: 0,
width: 200,
height: 400
};
var smallRectangle = {
width: 20,
height: 35
};
var numberOfRectangles = 6;
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.rect(bigRectangle.x, bigRectangle.y, bigRectangle.width, bigRectangle.height)
context.stroke();
for (var a = 0; a < numberOfRectangles; a++) {
context.rect(bigRectangle.x + bigRectangle.width, bigRectangle.y + (bigRectangle.height / numberOfRectangles) * (a + .5) - smallRectangle.height / 2, smallRectangle.width, smallRectangle.height)
context.stroke();
}
<canvas id="canvas" width=300 height=500></canvas>
代码的实现略有不同,因为您的循环从1开始
for (let i = 1; i <= noOfPortsToBeDrawn; i++) {
但是基本上,您只需要减去计算出的高度而不是相加即可,因此只需替换此行
const y = this.y + i * length - length / 2;
作者
const y = this.y + length * (i - 0.5) - height/2;