我的任务是在创建矩形后同时尝试在每个矩形中创建 9 个圆(每个角 4 个,侧面 4 个,中心 1 个)。我的解决方案在矩形外创建了 4 个圆圈,这是不可取的!
在创建矩形的同时,每个矩形应包含 9 个圆(每个角 4 个,侧面 4 个,中间 1 个)。
我使用 snap.svg 库来创建圆形和矩形。
您可以使用以下代码片段:
const svgId = 'campus_map';
const width = document.getElementById(svgId).viewBox.baseVal.width;
const height = document.getElementById(svgId).viewBox.baseVal.height;
let draw = Snap("#tiles");
let c = 0;
let size = Math.round(0.05 * width);
let circleSize = 25;
let circleColor = ["#ff0000", "#000000", "#00ffe1", "#0051ff"];
let svg = document.getElementById(svgId);
for (let i = 0; i <= width; i = i + size) {
for (let j = 0; j <= height; j = j + size) {
c += 1;
let rect = draw.rect(i, j, size, size);
let circle1 = draw.circle(i, j, circleSize);
let circle2 = draw.circle(i + (size / 2), j, circleSize);
let circle3 = draw.circle(i, j + (size / 2), circleSize);
let circle4 = draw.circle(i + (size / 2), j + (size / 2), circleSize);
rect.attr({
fill: "#d00bf3",
"fill-opacity": 0.2,
stroke: "#000",
"stroke-width": "1px",
id: "rect_" + c,
name: "rect" + c
});
circle1.attr({
fill: circleColor[0],
"fill-opacity": 1,
stroke: "#000",
"stroke-width": "1px",
id: "circle1_" + c,
name: "circle1_" + c
});
circle2.attr({
fill: circleColor[1],
"fill-opacity": 1,
stroke: "#000",
"stroke-width": "1px",
id: "circle2_" + c,
name: "circle2_" + c
});
circle3.attr({
fill: circleColor[2],
"fill-opacity": 1,
stroke: "#000",
"stroke-width": "1px",
id: "circle3_" + c,
name: "circle3_" + c
});
circle4.attr({
fill: circleColor[3],
"fill-opacity": 1,
stroke: "#000",
"stroke-width": "1px",
id: "circle4_" + c,
name: "circle4_" + c
});
}
}
<script src="https://unpkg.com/snapsvg@0.5"></script>
<svg viewBox="0 0 8204.08 6413.17" version="1.1" id="campus_map"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<g id="tiles"></g>
</svg>
问题的松散翻译在每个矩形中创建 9 个圆圈(每个角 4 个,侧面 4 个,中间 1 个)同时/在由 @Arif Ahmed立即创建一个矩形之后。
在您的循环中,您只为每个图块创建四个圆圈。如果再添加五个,您的代码将起作用。什么事拦住你了?
看起来您希望圆圈位于正方形内。为此,您需要将圆移动一个圆半径。
这是一个修改后的代码,我在其中计算了这个偏移量并使用一个循环来定位九个圆圈:
来自贡献者 @Paul LeBeau的答案的松散翻译 。
考虑使用 svg模式
这是解决您问题的最简单方法。
您可以随时轻松更改其内容、元素数量和形状。
您还可以填充任何形状的容器并使其具有响应性。
阅读代码中的注释,以更好地了解圆圈在一个图案拼贴中的位置。有关创建原理和模式示例的更多信息 -这里
填充剪影的示例,例如圣诞树: