如何在画布中获取组成一个圆圈的坐标数组? [英] How to get an array of coordinates that make up a circle in canvas?

查看:41
本文介绍了如何在画布中获取组成一个圆圈的坐标数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,如果这是我用来在画布上绘制圆圈的代码:

So, if this is the code I'm using to draw a circle on my canvas:

ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.stroke();

...我怎样才能获得组成这个圆的点的坐标数组,以便我可以将它们保存在数据库中并稍后使用 context.moveTo() 和 context.lineTo() 方法加载到画布上连接点,画同一个圆圈?

... how could I get an array of coordinates of the points that make up this circle so I can save them in a database and load on canvas later using the context.moveTo() and context.lineTo() methods to connect the dots, drawing the same circle?

我想我在问是否可以使用非 .arc() 方法绘制这种圆,而是通过用线连接点,如果我只知道我的中心坐标和圆半径(当然还有线条和颜色).这应该使我能够在循环时将每个点坐标保存在一个数组中.

I guess I'm asking if it's possible to draw this kind of circle using not .arc() method but by connecting dots with lines, if I only know my center coordinates and circle radius (and of course the width of the line and color). This should enable me to save each dot coordinates in an array as I loop through.

推荐答案

@Octopus 是在正确的轨道上:

@Octopus is on the right track:

var centerX=100;
var centerY=100;
var radius=40;

// an array to save your points
var points=[];

for(var degree=0;degree<360;degree++){
    var radians = degree * Math.PI/180;
    var x = centerX + radius * Math.cos(radians);
    var y = centerY + radius * Math.sin(radians);
    points.push({x:x,y:y});
}

然后就可以使用points数组中的点对象画圆了:

Then you can draw the circle using the point objects in the points array:

ctx.beginPath();
ctx.moveTo(points[0].x,points[0].y);
for(var i=1;i<points.length;i++){
    ctx.lineTo(points[i].x,points[i].y);
}
ctx.closePath();
ctx.fillStyle="skyblue";
ctx.fill();
ctx.strokeStyle="lightgray";
ctx.lineWidth=3;
ctx.stroke()

不过是个建议……

不用把所有的点都保存在数据库里,只把centerX/Y和radius都保存在数据库里.

Instead of saving all the points in the database, just save the centerX/Y and radius in the database.

然后您可以使用相同的数学来创建点并绘制圆.

Then you can use this same math to create the points and draw the circle.

这篇关于如何在画布中获取组成一个圆圈的坐标数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆