Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the coordinate points dynamically in svg

I am trying to create a triangle using SVG. I did so by following the tutorial. But the problem is that the coordinates are hardcoded. In the canvas I use to do it by getting the width and height from javascript.

in canvas

var width = document.getElementById('intro2').offsetWidth;
var height=document.getElementById('intro2').offsetHeight;
var canvas = document.getElementById("intro2canvas");
canvas.width=width;
canvas.height=height;
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "rgba(242,91,32,0.45)";
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(width/1.66,height);
ctx.lineTo(0,height);
ctx.closePath();
ctx.fillStyle="rgba(242,91,32,0.45)";
ctx.fill();

How to get the height and width value so that I can use that in SVG ??

like image 677
Nihar Avatar asked Feb 03 '26 03:02

Nihar


1 Answers

You can dynamically create and set width and height of svg as follows:

function createSVG(){
    svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
    svg.setAttribute('version', '1.1');
    svg.setAttribute('id', 'id'); //id for reffering your svg
    var canvas = document.getElementById('id'); //id of your container element
    width = canvas.getBoundingClientRect().width;
    height = canvas.getBoundingClientRect().height;
            svg.setAttribute('height', height);
            svg.setAttribute('width', width);
            canvas.appendChild(svg);
            //return svg;
}

for adding polygons dynamically you can use a function like

function drawPoly(points, fill, stroke) {

    var poly = document.createElementNS("http://www.w3.org/2000/svg","polygon");
    poly.setAttribute("points", points);
    poly.setAttribute("stroke", stroke);
    poly.setAttribute('fill', fill);

    svg.appendChild(poly); //where svg is referring to your svg element

            // return poly;
}

Afterwards you can create the polygon in tutorial dynamically like

drawPoly("10,0  60,0  35,50","#cc3333","#660000");

UPDATE: fiddle

UPDATE: fiddle with auto resize

like image 79
T J Avatar answered Feb 05 '26 20:02

T J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!