当前,我可以在整个SVG地图上而不是在每个LGA路径上显示六个标记:
我附加了一个js小提琴链接,您可以看到我当前的实现。
https://jsfiddle.net/eduhmik/7end8qLs/
代码在SVG地图上随机添加圆圈标记。该计数基于您使用名为circlesLength
的变量指定的长度。我希望每个路径上可能有四个标记,而不是SVG
const SVG_NS = 'http://www.w3.org/2000/svg';
document.querySelectorAll('path').forEach((item)=>{
item.setAttribute('class', 'path');
item.setAttribute('id', 'thePath');
})
const svg = document.getElementById('svg')
const lgaPath = document.getElementById('thePath')
/* .setAttribute('class','path').setAttribute('id','thePath') */
// the number of random points on the map
let circlesLength = 4;
// the bounding box of the path
/* let bb = thePath.getBBox(); */
//set the svg viewBox attribute
/* svg.setAttributeNS(null,"viewBox",`${bb.x} ${bb.y} ${bb.width} ${bb.height}`) */
// svg client rect
let cr = svg.getBoundingClientRect();
let n = 0;//a counter
for(let i = 0; i < 100; i++){
// get a random point on the svg canvas
let x = randomIntFromInterval(cr.x,(cr.x+cr.width));
let y = randomIntFromInterval(cr.y,(cr.y+cr.height));
//elementFromPoint returns the topmost Element at the specified coordinates (relative to the viewport).
let elmt = document.elementFromPoint(x, y);
// if the point is in path
if(elmt && elmt.className.baseVal == "path"){
//get the coordinates of the point on the svg
let svgPoint = getPoint(x,y);
//draw a circle with the center on the svg point
drawCircle({cx:svgPoint.x,cy:svgPoint.y,r:.01}, svg)
//incerase the counter
n++
};
// if you already have 6 points break the loop
if(n == circlesLength){break;}
}
// a function to get a random integer from an interval
function randomIntFromInterval(mn, mx) {
return ~~(Math.random() * (mx - mn + 1) + mn);
}
// a function to get the svg coordinates of a point on the svg canvas
function getPoint(x,y){
var p = svg.createSVGPoint();
p.x = x;
p.y = y;
var ctm = svg.getScreenCTM().inverse();
var p = p.matrixTransform(ctm);
return p;
}
// a function to draw a circle
function drawCircle(o, parent) {
var circle = document.createElementNS(SVG_NS, 'circle');
for (var name in o) {
if (o.hasOwnProperty(name)) {
circle.setAttributeNS(null, name, o[name]);
}
}
parent.appendChild(circle);
return circle;
}