大家好,我正在尝试使用半圆在 Canvas 上绘制一条简单的彩虹。我的第一个圈子创建成功了。
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
<script>
var omkadering = document.getElementById("myCanvas");
var context = omkadering.getContext("2d");
context.beginPath();`
context.arc(95,100,80,3.1,2*Math.PI);
context.lineWidth = 10;
context.strokeStyle = "violet";
context.stroke();
</script>
</body>
</html>
这实际上工作得很好我已经完成了第一层 first layer
然后我尝试制作第二个,所以我添加了这部分
context.strokeStyle = "violet";
-- started new code here --
context.closePath();
context.beginPath();
context.arc(95,120,80,3.1,2*Math.PI);
context.strokeStyle = "indigo";
-- new code ends here --
context.stroke();
</script>
</body>
</html>
但是它覆盖了旧层
我也尝试了其他几种方法,比如创建一个新的变量上下文或将它们彼此分开,但都没有帮助
有没有人知道我做错了什么或忘记添加?
提前致谢!
伊恩·德塞斯
最佳答案
您应该更改圆弧的半径,而不是圆心。
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
var arcWidth = 10;
var radius = 8 * arcWidth;
var omkadering = document.getElementById("myCanvas");
var context = omkadering.getContext("2d");
omkadering.width = (radius + (colors.length-0.5) * arcWidth) * 2;
omkadering.height = (radius + (colors.length-1) * arcWidth);
var drawArc = function( color ){
context.beginPath();
context.arc(
omkadering.width/2,
omkadering.height + arcWidth/2,
radius,
Math.PI,
2*Math.PI
);
context.lineWidth = arcWidth;
context.strokeStyle = color;
context.stroke();
context.closePath();
radius += arcWidth;
};
colors.reverse().forEach( drawArc );
<canvas id="myCanvas" style="border:1px solid #000000;"></canvas>
关于javascript - 用 canvas 和 javascript 绘制彩虹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700784/