如何用svg在循环中绘制Bezier曲线

如何用svg在循环中绘制Bezier曲线

本文介绍了如何用svg在循环中绘制Bezier曲线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道要绘制bezier曲线你使用:

So i know that to draw bezier curve you use:

path.setAttributeNS(null, "d", "M5,5 C5,45 45,45 45,5"):

但我想画它们在循环(不是动画)并且每次都改变它们的位置,它每次都是相同的曲线,但具有不同的开始和结束位置。而且我不知道如何在循环中更改这些属性。

but i would like to draw them in loop (not animation) and change their location every time, it will be same curve every time but with difrent start and end location. And i dont know how to change those attributes in loop.

从下面的回答中我尝试了我的代码,但它不起作用。我知道我做错了什么,但我不知道是什么。以下是modyfication后的代码:

From answer from bellow i tryd in my code but it dont work. I know i did something wrong but i dont know what. Here is my code after modyfication:

for (var i = 0; i < 100; i++) {
var x1 = 10;
var x2 = 15;
var x3 = 20;
var x4 = 30;
var x5 = 40;
var x6 = 50;
var x7 = 60;
var x8 = 70;

var attr = "M" + x1 + "," + x2 + " " + "C" + x3 + "," + x4 + " " + x5 "," + x6 + " " + x7 + "," + x8;

var path = document.createElementNS(svgns, 'path');
path.setAttributeNS("d", attr);
path.setAttributeNS(null, "fill", "none");
path.setAttributeNS(null, 'stroke', '#'+Math.round(0xffffff * Math.random()).toString(16));
document.getElementById('svgOne').appendChild(path);

}

x`s只是为了测试它是否有效,所以我犯了错误???

x`s are just to test if it works, so where i have made mistake???

推荐答案

你可以重新构造字符串:

You could recontruct the string:

var x1 = 5;
var x2 = 5;
var attr = "M" + x1 + "," + x2 + " C" + ...

path.setAttribute("d", attr);

或者使用因此,如果您已经有一条贝塞尔曲线

Or alternatively use the SVG DOM so if you already have a single bezier curve

var move = path.pathSegList.getItem(0);
var curve = path.pathSegList.getItem(1);

然后你可以使用界面设置曲线属性,例如

then you can use the SVGPathSegCurvetoCubicAbs interface to set the curve attributes e.g.

curve.x = 5;
curve.y = 10;
curve.x1 = 20
curve.y1 = 15;
curve.x2 = 12;
curve.y2= 13;

在您的尝试中

var attr = "M" + x1 + "," + x2 + " " + "C" + x3 + "," + x4 + " " + x5 "," + x6 + " " + x7 + "," + x8;

                                                                      ^ missing + sign

path.setAttributeNS("d", attr);

setAttributeNS需要3个参数,或者setAttribute需要2个。

setAttributeNS takes 3 arguments or alternatively setAttribute takes 2.

path.setAttributeNS(null, 'stroke', '#'+Math.round(0xffffff * Math.random()).toString(16));

这并不总是产生有效的笔画语法,虽然偶尔会这样做,你会看到一些输出。

this does not always produce valid stroke syntax although occasionally it does so you will see some output some times.

浏览器会在错误/网络控制台中报告这些问题,所以你真的应该尝试利用它。

browsers will report these issues in their error/web consoles so you really should try to take advantage of that.

这篇关于如何用svg在循环中绘制Bezier曲线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:49