gpt4 book ai didi

javascript - 使用具有额外线条的 JavaScript 在 HTML Canvas 上绘制多个椭圆形

转载 作者:行者123 更新时间:2023-11-29 11:00:20 25 4
gpt4 key购买 nike

我想了解更多关于 HTML Canvas 和 JavaScript 的信息。现在我试图绘制多个相互重叠的椭圆形,并且尺寸会一个接一个地变小。我可以成功绘制形状。

这是我的代码

<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
</canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var center_x = 200;
var center_y = 100;
var width = 100;
var height = 200;
drawOvalShape(context, 200, 100, 100, 200);
drawOvalShape(context, 200, 100, 80, 180);
drawOvalShape(context, 200, 100, 60, 160);
drawOvalShape(context, 200, 100, 40, 140);
drawOvalShape(context, 200, 100, 20, 120);

function drawOvalShape(context, center_x, center_y, width, height){
context.ellipse(center_x, center_y, width, height, 90 * Math.PI/180, 0, 2 * Math.PI);

context.stroke();
}
</script>

当我在浏览器上运行我的代码时,它显示如下。

enter image description here

但问题是为什么要像下面这样包含额外的一行?

enter image description here

我怎样才能摆脱那条线?

最佳答案

您缺少 context.beginPath。请查看此 JSFIddle:https://jsfiddle.net/zwcd7hcw/

function drawOvalShape(context, center_x, center_y, width, height){
context.beginPath()
context.ellipse(center_x, center_y, width, height, 90 * Math.PI/180, 0, 2 * Math.PI);
context.stroke();
}

 var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var center_x = 200;
var center_y = 100;
var width = 100;
var height = 200;
drawOvalShape(context, 200, 100, 100, 200);
drawOvalShape(context, 200, 100, 80, 180);
drawOvalShape(context, 200, 100, 60, 160);
drawOvalShape(context, 200, 100, 40, 140);
drawOvalShape(context, 200, 100, 20, 120);

function drawOvalShape(context, center_x, center_y, width, height){
context.beginPath()
context.ellipse(center_x, center_y, width, height, 90 * Math.PI/180, 0, 2 * Math.PI);

context.stroke();
}
<canvas id="myCanvas" width="400" height="200" style="border:1px solid #000000;">
</canvas>

关于javascript - 使用具有额外线条的 JavaScript 在 HTML Canvas 上绘制多个椭圆形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48252428/

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