gpt4 book ai didi

javascript - 如何使用for循环在canvas中绘制圆形曲线?

转载 作者:行者123 更新时间:2023-12-03 21:28:47 25 4
gpt4 key购买 nike

我想使用 for 循环在圆形中绘制贝塞尔曲线。到目前为止,我无法在圆形模式下放置任何贝塞尔曲线,但这些曲线不是弯曲的,它们只是直线,因为我无法正确更改 handle ,这将使这些曲线弯曲。你可以在这里看到我的代码,请让我知道我的错误。

我也尝试过将颜色填充到曲线中,但这并没有发生,我也不知道为什么。

<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>

最佳答案

如果您需要重复一条曲线,那么最简单的方法就是只定义一次,而不是自己计算所有新点,只需让您的 Canvas 移动即可。

将 Canvas 想象成一张可移动的纸。您可以使用 ctx.setTransformctx.rotatectx.translate 等来“移动”此 Canvas ,同时将笔保持在相同的位置。

这样,您可以定义一次路径,然后在不同位置绘制多次:

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>

关于javascript - 如何使用for循环在canvas中绘制圆形曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60405406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com