Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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/svg.js@3.0/dist/svg.min.js"></script>
<body/>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!