如何用SVG绘制正弦波模式

时间:2014-04-09 07:14:19

标签: html5 svg vector-graphics sine

我正试图改变以下模式......

enter image description here

......成为一个完美的正弦波模式。我应该使用哪些控制点(如何计算它们?)?我是否还必须使图案更宽?

以下是如何生成上述内容:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="800" width="800">
    <defs>
        <!-- Geometry -->
        <g>
            <rect id="square" x="0" y="0" width="200" height="200" />
        </g>

        <!-- Patterns -->
        <pattern id="wave" x="0" y="0" width="10" height="10" patternUnits="userSpaceOnUse">
            <path d="M 0 7.5 Q 2.5 7.5 2.5 5 Q 2.5 2.5 5 2.5 Q 7.5 2.5 7.5 5 Q 7.5 7.5 10 7.5"  stroke="black" fill="transparent" stroke-width="1" stroke-linecap="square" stroke-linejoin="miter" />
        </pattern>
    </defs>

    <!-- Graphics -->
    <use xlink:href="#square" transform="translate(000, 000)" fill="url(#wave)"/>
</svg>

要玩的演示在这里:http://jsfiddle.net/uEULF/

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

使用Asad的答案中的示例:How to draw sine waves with SVG (+JS)?

以下是演示:http://jsfiddle.net/HyTad/

var svg = document.getElementById('sine_wave').children[0];
var origin = { //origin of axes
    x: 100,
    y: 100
};
var amplitude = 10; // wave amplitude
var rarity = 1; // point spacing
var freq = 0.1; // angular frequency
var phase = 20; // phase angle

for (var i = -100; i < 1000; i++) {


    var line = document.createElementNS("http://www.w3.org/2000/svg", "line");

    line.setAttribute('x1', (i - 1) * rarity + origin.x);
    line.setAttribute('y1', Math.sin(freq * (i - 1 + phase)) * amplitude + origin.y);


    line.setAttribute('x2', i * rarity + origin.x);
    line.setAttribute('y2', Math.sin(freq * (i + phase)) * amplitude + origin.y);

    line.setAttribute('style', "stroke:black;stroke-width:1");

    svg.appendChild(line);
}