如何在SVG中动态设置坐标点 [英] How to set the coordinate points dynamically in svg

查看:1079
本文介绍了如何在SVG中动态设置坐标点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用SVG创建一个三角形.我是按照教程进行操作的.但是问题是坐标是硬编码的. 在画布中,我通常通过从javascript获取宽度和高度来做到这一点.

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.

在画布上

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();

如何获取高度和宽度值,以便可以在SVG中使用它?

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

推荐答案

您可以动态创建和设置svg的宽度和高度,如下所示:

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

这篇关于如何在SVG中动态设置坐标点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆