【问题标题】:html5 canvas draw lines in a circlehtml5画布在一个圆圈中画线
【发布时间】:2018-05-07 10:58:33
【问题描述】:

我在用 html5 画布画圆圈时遇到了一些麻烦。 我试图让这些条看起来像这样

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

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    处理这种可视化的最简单方法是使用上下文的转换矩阵。

    你需要理解它,就像你手里拿着一张纸一样。 不要试图以正确的角度画线,而是旋转纸张,并始终以相同的方向画线。

    这样,您在绘图方法中只需要角度和每个条的高度。

    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>

    【讨论】:

    • 这里的唯一代码对我也有帮助,但我选择了另一个,因为它使用了相同的现有代码。谢谢!!!你给我的纸上类比对我帮助很大。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      检查你的codepen,发现问题出在degrees_to_radians

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

      PS 我只看圆的形状而不是条的对齐方式:D

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-24
        • 1970-01-01
        • 2021-12-31
        相关资源
        最近更新 更多