Javascript 使用画布在父矩形上绘制与图像中相同的随机矩形
我有一个父矩形,我想在父矩形的右角添加多达10个或更少的矩形,如图所示 我写了一个这样做的代码,但它没有从父矩形的中心对齐Javascript 使用画布在父矩形上绘制与图像中相同的随机矩形,javascript,typescript,canvas,html5-canvas,Javascript,Typescript,Canvas,Html5 Canvas,我有一个父矩形,我想在父矩形的右角添加多达10个或更少的矩形,如图所示 我写了一个这样做的代码,但它没有从父矩形的中心对齐 this.addPortsToTheTransponder(3); addPortsToTheTransponder(noOfPortsToBeDrawn: number) { for (let i = 1; i <= noOfPortsToBeDrawn; i++) { this.createPorts(i, noOfPortsToBeDraw
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查看它是否始终居中于大矩形的一侧: 变量bigRectangle={ x:0,, y:0, 宽度:200, 身高:400 }; var smallRectangle={ 宽度:20, 身高:35 }; var numberOfRectangles=6; var canvas=document.getElementByIdcanvas; var context=canvas.getContext2d; context.rectbigRectangle.x,bigRectangle.y,bigRectangle.width,bigRectangle.height 中风; 对于var a=0;a<多个矩形;a++{ context.rectbigRectangle.x+bigRectangle.width,bigRectangle.y+bigRectangle.height/numberOfRectangles*a+.5-smallRectangle.height/2,smallRectangle.width,smallRectangle.height 中风; }
我完善了上面的答案。如果你能在StackBlitz上使用我的代码,那就太好了。我不是那里的注册用户,所以我无法保存任何修改,但我实际上只是替换了app.component.ts const y=this.y+I*length-length/2的第60行;常数y=该.y+长度*i-0.5-高度/2;您可以保存并单击forkNo problem@anonymous-很高兴我能帮上忙!