我正在尝试使用SVG创建一个三角形。我按照tutorial这样做了。但问题是坐标是硬编码的。 在画布中我通过从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中使用它
答案 0 :(得分:2)
您可以动态创建和设置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");
更新:fiddle
更新:fiddle并自动调整大小