Trouble Creating Dynamic Polygons with JavaScript and CSS

33 views Asked by At

I'm trying to create a polygon shape dynamically using JavaScript and CSS. I have a function that takes coordinates (x, y), radius, number of sides, and color. The function calculates the coordinates of each vertex based on these parameters and then creates a polygon using CSS `clip-path`. However, when I call this function with the desired parameters, the shape is not displaying correctly on the webpage.

Here's the function I'm using:

const container = document.querySelector("#container");

document.querySelector("#polygon-tool").addEventListener("click", ()=>{
    drawPolygon(100, 100, 40, 3, 'blue');
})

function drawPolygon (x, y, radius, sides, color) {
    const shape = document.createElement("div");
    shape.classList.add("resizable-shape");

    // Calculate the angle between each vertex
    const angleIncrement = (2 * Math.PI) / sides;

    // Calculate the coordinates of each vertex
    const vertices = [];
    for (let i = 0; i < sides; i++) {
        const xPos = x + radius * Math.cos(angleIncrement * i);
        const yPos = y + radius * Math.sin(angleIncrement * i);
        vertices.push(`${xPos}px ${yPos}px`);
    }

    // Create the polygon path
    const polygonPath = `polygon(${vertices.join(", ")})`;

    // Apply styles
    shape.style.clipPath = polygonPath;
    shape.style.backgroundColor = color;
    shape.style.position = "absolute";
    shape.style.left = x + "px";
    shape.style.top = y + "px";

    // Add shape to container
    container.appendChild(shape);
}

Expectation: The function drawPolygon should correctly display a polygon shape on the webpage with the specified number of sides and color parameters.

0

There are 0 answers