[英]Drawing random rectangles on the parent rectangle as in the image using canvas
我有父矩形,我想在父矩形的右上角添加最多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();
}
无论小矩形的总数如何,如何始终对齐从中心绘制的小矩形? 这是代码
只涉及一点数学。 假设您的大矩形位于x = 20,y = 20,其宽度为200,高度为300。
现在,您要在其右侧绘制5个较小的矩形。
考虑到这一点,您知道5个小矩形的最大垂直空间是大矩形的高度-300-因此让我们将300除以5得到60。如果您只是开始以y开头每60像素绘制一个小矩形大矩形的位置,小矩形将与顶部对齐。 这里的技巧是将计算出的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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.