Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在svg中动态设置坐标点_Javascript_Html_Svg - Fatal编程技术网

Javascript 如何在svg中动态设置坐标点

Javascript 如何在svg中动态设置坐标点,javascript,html,svg,Javascript,Html,Svg,我正在尝试使用SVG创建一个三角形。我这样做是通过遵循规则。但问题是坐标是硬编码的。 在画布中,我通过从javascript获取宽度和高度来实现这一点 在画布上 var width = document.getElementById('intro2').offsetWidth; var height=document.getElementById('intro2').offsetHeight; var canvas = document.getElementById("intro2canvas"

我正在尝试使用SVG创建一个三角形。我这样做是通过遵循规则。但问题是坐标是硬编码的。 在画布中,我通过从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中使用???

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

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;
}
要动态添加多边形,可以使用以下函数

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;
}
之后,您可以在教程中动态创建多边形,如

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


更新:使用自动调整大小

功能应位于svg标记内部或JS内部。我需要将点值设置为宽度/1.5或类似的值,那么你提到的函数将在JavaScriptor中编写,它应该在javascript中编写。我不想做的是,因为分辨率会变化,多边形也会变化,我猜,这就是为什么我想使用width/1.5,height/1.8这样的值,以便它在任何screenvar poly=drawPoly中保持成比例(“10,0 60,0 35,50”,“#cc3333”,“#660000”);除此之外,我想使用类似于var poly=drawPoly的东西(“0,0宽度/1.66,高度0,高度”,“#cc3333”,“#660000”);除了您的解决方案对我绝对正确之外,我无法实现