使用Snap.svg创建矩形时同步生成内部9个圆形的问题求助
问题根因
现有代码仅生成了左上角、上边中点、左边中点、中心4个圆形,缺少右上角、右下角、左下角、下边中点、右边中点5个目标位置的圆形,不符合9个点位的要求。
修正代码
补充剩余5个圆形的创建逻辑即可,完整JS代码如下:
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; // 颜色数组已扩容到9个,对应9个圆形,可按需修改色值 let circleColor = ["#ff0000", "#000000", "#00ffe1", "#0051ff", "#ff8800", "#00ff00", "#ff00ff", "#ffff00", "#8844ff"]; 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); // 9个圆形按位置依次创建:4个角→4个边中点→中心 let circle1 = draw.circle(i, j, circleSize); // 左上角 let circle2 = draw.circle(i + size, j, circleSize); // 右上角 let circle3 = draw.circle(i, j + size, circleSize); // 左下角 let circle4 = draw.circle(i + size, j + size, circleSize); // 右下角 let circle5 = draw.circle(i + (size / 2), j, circleSize); // 上边中点 let circle6 = draw.circle(i + (size / 2), j + size, circleSize); // 下边中点 let circle7 = draw.circle(i, j + (size / 2), circleSize); // 左边中点 let circle8 = draw.circle(i + size, j + (size / 2), circleSize); // 右边中点 let circle9 = 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 }); circle5.attr({ fill: circleColor[4], "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: "circle5_" + c, name: "circle5_" + c }); circle6.attr({ fill: circleColor[5], "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: "circle6_" + c, name: "circle6_" + c }); circle7.attr({ fill: circleColor[6], "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: "circle7_" + c, name: "circle7_" + c }); circle8.attr({ fill: circleColor[7], "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: "circle8_" + c, name: "circle8_" + c }); circle9.attr({ fill: circleColor[8], "fill-opacity": 1, stroke: "#000", "stroke-width": "1px", id: "circle9_" + c, name: "circle9_" + c }); } }
HTML代码无需修改,保持原有引入和结构即可。
内容的提问来源于stack exchange,提问作者Arif Ahmed
相关产品推荐
相关产品推荐

