Как нарисовать кривые в кругу на холсте, используя для l oop? - PullRequest
4 голосов
/ 26 февраля 2020

Я хочу нарисовать кривые Безье по кругу, используя для l oop. До сих пор я не мог поставить кривые Безье в круговом режиме, но эти кривые не изогнуты, это просто прямые линии, потому что я не смог правильно изменить ручку, которая сделает эти кривые изогнутыми. Вы можете увидеть мой код здесь, пожалуйста, дайте мне знать о моих ошибках.

Я также пытался залить цвет в кривые, но этого тоже не происходит, и я не знаю почему.

<html>
    <body>
        <style>
            *{
                margin: 0px;
            }
            body{
                background-color: aqua;
            }
            canvas
            {
                background-color: white;
            }
        </style>
        <canvas id="mycanvas"></canvas>
        <script>
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x = window.innerWidth/2;
y = window.innerHeight/2;
r = window.innerWidth;
theta = 0.1;

for(theta=0.1; theta<12.6; theta+=0.1) {
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.bezierCurveTo(x,y,x,y, x+ r * Math.cos(theta),y + r * Math.sin(theta));
    ctx.lineWidth = 1;
    ctx.strokeStyle = "black";
    ctx.stroke();
    ctx.closePath();
    ctx.fill();
}
            
for ( i=r/16; i < r; i=i+r/12 ) {
    ctx.beginPath();
    ctx.arc(x, y, i, 0, 2 * Math.PI, false);
    ctx.stroke();
}  

                
    
        </script>
    </body>
</html>

1 Ответ

0 голосов
/ 26 февраля 2020

Если вам нужно повторить одну кривую, то самое простое - определить ее только один раз, а вместо того, чтобы рассчитывать все новые точки, просто заставить свой холст двигаться.

Думайте о своем холсте как о подвижный лист бумаги. Вы можете использовать ctx.setTransform, ctx.rotate, ctx.translate et c. «переместить» этот холст, держа ручку в том же положении.

Таким образом, вы можете один раз определить свой путь и нарисовать его несколько раз в разных позициях:

var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');

const angle = 0.1; // by which amount we rotate at each iteration

function draw() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  const cx = window.innerWidth/2;
  const cy = window.innerHeight/2;
  const rad = Math.max(cx, cy) * 2;
  // controls the position of all the control points,
  // you might want to set each manually instead
  const binding = rad/Math.PI;
  let theta = 0;

  // we move our canvas so its center is now coordinates 0,0
  ctx.setTransform(1, 0, 0, 1, cx, cy);
  // a single path declaration
  ctx.beginPath();
  for( theta; theta < Math.PI*4; theta += angle ) {
    ctx.rotate(angle); // apply the rotation
    ctx.moveTo(0, 0); // current center
    // always the same parameters for the bezier curve
    ctx.bezierCurveTo(0, -binding, rad, -binding, rad, 0);
  }
  // even these can be part of the same single path
  for ( i=rad/8; i < rad; i += rad/8 ) {
    ctx.moveTo(i, 0); // to avoid the segment from center
    ctx.arc(0, 0, i, 0, 2 * Math.PI, false);
  }
  // a single stroke of the whole path
  ctx.stroke();
  
  // to reset the coordinate 0,0 at top left corner
  ctx.setTransform(1,0,0,1,0,0);
}

draw();
onresize = draw;
root,body { background: white; margin: 0 }
canvas { display: block; }
<canvas id="mycanvas"></canvas>
...