HTML5画布如何在圆形中绘制线条

3
我在使用HTML5画布时遇到了绘制圆形中的线条问题。我试图让柱状图看起来像这样:enter image description here
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var bars = 50;
var radius = 100;
for(var i = 0; i < bars; i++){
  var x = radius*Math.cos(i);
  var y = radius*Math.sin(i);
  draw_rectangle(x+200,y+200,1,13,i, ctx );
}


function draw_rectangle(x,y,w,h,deg, ctx){
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(degrees_to_radians(deg));
  ctx.fillStyle = "yellow";
  ctx.fillRect(-1*(w/2), -1*(h/2), w, h);
  ctx.restore();
}
function degrees_to_radians(degrees){
  return degrees * Math.PI / 180;
}
function radians_to_degrees(radians){
  return radians * 180 / Math.PI;
};

由于某种原因,我的线条都是歪的,对齐不了。我真的需要帮助。 https://codepen.io/anon/pen/PRBdYV

4个回答

6
最简单处理此类可视化的方法是使用上下文的转换矩阵进行操作。 需要将其理解为手中拿着一张纸。 不要试图在正确的角度绘制线条,而是旋转纸张,并始终朝同一个方向绘制线条。 这样您在绘图方法中只需要角度和每个柱子的高度即可。

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
// the position of the whole thing
var circleX = canvas.width / 2;
var circleY = canvas.height / 2;
//
var bars = 50;
var barWidth = 5;
// inner radius
var radius = 50;
ctx.fillStyle = "yellow";
// no need to use degrees, a full circle is just 2π
for(var i = 0; i < Math.PI*2; i+= (Math.PI*2 / bars)){
  draw_rectangle(i, (Math.random()*30) + 10);
}

function draw_rectangle(rad, barHeight){
  // reset and move to the center of our circle
  ctx.setTransform(1,0,0,1, circleX, circleY);
  // rotate the context so we face the correct angle
  ctx.rotate(rad);
  // move along y axis to reach the inner radius
  ctx.translate(0, radius);
  // draw the bar
  ctx.fillRect(
    -barWidth/2, // centered on x
    0, // from the inner radius
    barWidth,
    barHeight // until its own height
  );
}
canvas#canvas{
  background:black;
}
<html>
  <body>
    <canvas id="canvas" width="400" height="400"></canvas>
  </body>
</html>


这个代码确实对我有所帮助,不过我选择了另一个,因为它使用了相同的现有代码。谢谢!你给我的纸张类比帮了我很多。 - Plixxer

0

检查你的 CodePen,发现问题在于 degrees_to_radians 函数。

这是你的代码更新链接。Link

PS:我只看了圆的形状,没有注意条形的对齐方式 :D


0

https://codepen.io/anon/pen/YajONR

问题已解决:Math.cos需要弧度而非角度。 我们需要从0到360,所以我调整了条形数量使其更容易,并将i乘以6(因此最大值为60*6==360)。 如果在绘制条形时不添加+90,我们只会得到一个圆形。

0

你也可以使用线条来达到相同的效果;

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var bars = 50;

var r = 100;

let slice = (Math.PI * 2) / bars
let angle = 1; 
for(var i = 0; i < bars; i++){
  var x = Math.cos(angle)*30;
  var y = Math.sin(angle)*30;
  draw_rectangle(x,y,1,13,ictx );
  angle += slice
}


function draw_rectangle(x,y,ctx){
  
  var size = Math.random()*5+1
 
  ctx.beginPath()
  ctx.strokeStyle='red'
  ctx.moveTo(x+r, y+r);
  ctx.lineTo(x*size+r, y*size+r);
  ctx.stroke();
  //ctx.restore();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接