'Adding array of points to polygon

Im trying to programmatically create an SVG polygon with a function by adding to the polygons array using svg.js using the following code:

const draw = SVG().addTo('body').attr({
  viewBox: '0 0 100 100'
})

const {width,height} = draw.viewbox()

const polygon = draw.polygon([])


createPoint(0,0)
createPoint(100,0)
createPoint(100,100)

function createPoint(x,y){
  const point = new SVG.Point()
  point.x = x
  point.y = y
  polygon.array().push([point.x,point.y])
}

Nothing is displayed in the svg. Any ideas? Thanks in advance



Solution 1:[1]

You're not pushing the new points to the previously created array.

You could instead set a point variable which will receive newly created points

let points = [];
createPoint(0,0)
createPoint(100,0)
createPoint(100,100)

const draw = SVG().addTo('body').attr({
  viewBox: '0 0 100 100'
})
const draw2 = SVG().addTo('body').attr({
  viewBox: '0 0 100 100'
})

let points = [];
createPoint(0,0)
createPoint(100,0)
createPoint(100,100)

let points2 = [];
addPoint(0,0);
addPoint(100,0);
addPoint(100,100);


const polygon = draw.polygon(points)
const polygon2 = draw2.polygon(points)

function createPoint(x,y){
  const point = new SVG.Point()
  point.x = x
  point.y = y
  points.push([point.x,point.y])
}

function addPoint(x,y){
  points2.push([x, y])
}
svg{
  display:inline-block;
  width:20%
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/3.1.2/svg.min.js"></script>

But I'm not sure why you need to create new svgPoints.
Simple x/y coordinates would also do the trick.

Solution 2:[2]

I had the same hunch as @herrstrietzel, who posted 18sec ago :-). Here's a fix preserving most of the initial OP code...

const draw = SVG().addTo('body').attr({
  viewBox: '0 0 100 100'
})

const {width,height} = draw.viewbox()

let pts = [];

function createPoint(x,y){
  const point = new SVG.Point()
  point.x = x
  point.y = y
  pts.push([point.x,point.y])
}

createPoint(5,5)
createPoint(25,25)
createPoint(35,10)

const polygon = draw.polygon(pts)
<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>
<body/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 herrstrietzel
Solution 2 danh