Home > Mobile >  Include the output of a js script in the front
Include the output of a js script in the front

Time:08-06

I have this js script

// Just setup, not related to problem.
const svg = d3.select("body")
  .append("svg")
    .attr("width", 500)
    .attr("height", 500);
    
const circle = svg.append("circle")
    .attr("cx", "150")
    .attr("cy", "150")
    .attr("r", "100")
    .attr("fill", "none")
    .attr("stroke", "black");
    
const polygon = svg.append("polygon")
    .attr("fill", "none")
    .attr("stroke", "blue");
    
const circleElement = circle.node();
const ranger = d3.select("#ranger").on("input", update);
const label = d3.select("label");

// This function contains all the relevant logic.
function update() {
  let count = ranger.node().value;
  label.text(count);
  // Calculate step length as circumference / number of points.
  const step = circleElement.getTotalLength() / count; 
  // Build an array of all points on the circle.
  const data = Array.from({length: count}, (_, i) => {
    const point = circleElement.getPointAtLength(i * step);   // Get coordinates of next point.
    return `${point.x},${point.y}`; 
  });
  polygon.attr("points", data.join(" "));
}

update();

And I have this html code:

 <body>
 <center>
 <div >

Number of side of the polygon.
<script src="https://d3js.org/d3.v5.js"></script>
    <p>
  <input id="ranger" type="range" min="3" max="32" value="5">
  <label for="ranger"></label>
</p>

</div>
</center>
</body>

As you can see on the picture we get an output. I want the output or the figure to be in center like the above so it's not in the left corner anymore. How can I do this? enter image description here

  1. Also, if I want to have a new output that returns the value in a array (for example the alphabet) in the squarre as shown in the picture, how can I do that? So when we drag for number 2 the letter B should appear in the squarre and if we drag to number 3 the letter C should be in the squarre.

  2. Is it also possible to make the line (where we drag) longer?

enter image description here

CodePudding user response:

you can set svg in css like this:

svg {
  display: block;
  margin: auto;
  width: 300px;
  height: 300px;
} 

should be working fine:) https://jsfiddle.net/bqkt6r84/

ps: had to change the width and height because by default it was 500x500

  • Related