使用JavaScript创建SVG向量

使用JavaScript创建SVG向量,javascript,variables,svg,vector,Javascript,Variables,Svg,Vector,我试图找到一种创建SVG多段线的方法,其中每个点的“x”和“y”值定义为JavaScript文件生成的值。这些数字基于一系列带有if/else条件的随机变量 我已经准备好了用于绘制这些点的JavaScript文件,但是我不知道如何将变量id链接到SVG脚本中。这有可能吗?有人知道如何做到这一点吗 干杯 试试这个 var svgns = "http://www.w3.org/2000/svg"; var svgDocument = evt.target.ownerDocument; var sha

我试图找到一种创建SVG多段线的方法,其中每个点的“x”和“y”值定义为JavaScript文件生成的值。这些数字基于一系列带有if/else条件的随机变量

我已经准备好了用于绘制这些点的JavaScript文件,但是我不知道如何将变量id链接到SVG脚本中。这有可能吗?有人知道如何做到这一点吗

干杯

试试这个

var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r",  20);
shape.setAttributeNS(null, "fill", "green"); 

您可以找到一个关于创建SVG对象的优秀教程

SVG是一个文档,而不是一个脚本。脚本是一段可执行代码,通常使用Javascript

首先:获取SVG对象。例如,如果您的svg嵌入到网页中:

var svg = document.getElementById("yourSVGObject"); /* If <svg id="yourSVGObject"> */
要将多段线添加到SVG对象,请执行以下操作:

var polyline = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
polyline.style.fill = "none";
polyline.style.stroke = "#ff0000";
polyline.style.strokeWidth = "2px";
svg.appendChild(polyline);
要修改多段线上的点,需要一次修改所有点。您必须提供一个字符串,而不是一组点:

polyline.setAttributeNS(null, "points", "10,10 90,20 170,50");
请注意,多段线元素仅绘制直线。如果你想,比如说,在每个点上画圆,你必须为每个点加一个圆

如果已将点存储在阵列上:

var polylinePoints = [];
var circles = []; /* Optional */
for(var i = 0; i < points.length; i++) {
    polylinePoints.push(points[i].x + ", " + points[i].y);
    var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    circle.setAttributeNS(null, "cx", points[i].x);
    circle.setAttributeNS(null, "cy", points[i].y);
    circle.setAttributeNS(null, "r", 8); /* This is the radius of the circle */
    circle.setAttributeNS(null, "class", "polylinePoint"); /* You can style individual shapes using CSS */
    circles.push(circle); /* Optional */
    svg.appendChild(circle);
}
polyline.setAttributeNS(null, "points", polylinePoints.join(" "));

小提琴示例:

当我开始练习时,我似乎得到了更快、更好、更多的答案。可能是因为对其他人来说,复制/粘贴/修改比从头开始编写示例要容易得多,而且程序员可以更普遍地阅读代码以快速发现问题,而不管问题是用什么语言编写的。非常感谢。我将阅读教程,但我想我知道我需要做什么,从你所描述的。
var polylinePoints = [];
var circles = []; /* Optional */
for(var i = 0; i < points.length; i++) {
    polylinePoints.push(points[i].x + ", " + points[i].y);
    var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
    circle.setAttributeNS(null, "cx", points[i].x);
    circle.setAttributeNS(null, "cy", points[i].y);
    circle.setAttributeNS(null, "r", 8); /* This is the radius of the circle */
    circle.setAttributeNS(null, "class", "polylinePoint"); /* You can style individual shapes using CSS */
    circles.push(circle); /* Optional */
    svg.appendChild(circle);
}
polyline.setAttributeNS(null, "points", polylinePoints.join(" "));
shape.remove(); /* e.g. circle[5].remove(); polyline.remove(); */