代码之家  ›  专栏  ›  技术社区  ›  Morfinismo

画布圆绘制不正确

  •  0
  • Morfinismo  · 技术社区  · 6 年前

    我想用画布做一个模拟时钟。第一步是画一个圆,但由于某些原因,这个圆没有被正确地画出来。圆圈不完整。这就是我要做的:

    var canvas = document.createElement("canvas");
    canvas.style.height = "250px";
    canvas.style.width = "250px";
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(125, 125, 70, 0, 2 * Math.PI);
    ctx.stroke()
    ctx.closePath();
    window["clock"].appendChild(canvas);
    #clock{
      width: 250PX;
      height: 250px;
      border: 1px solid gray;
    }
    <div id="clock">
    </div>

    我真的很难理解为什么圆圈画得不好。不过,我需要这个充满活力。有人能帮我弄明白怎么做吗?谢谢。

    3 回复  |  直到 6 年前
        1
  •  2
  •   Eriks Klotins    6 年前

    您需要正确设置画布宽度和高度属性。现在使用默认值(300x150)并将其拉伸为正方形。这就是为什么你的图像看起来有偏差。

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/width https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/height

    var canvas = document.createElement("canvas");
    canvas.height = 250;
    canvas.width = 250;
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(125, 125, 70, 0, 2 * Math.PI);
    ctx.stroke()
    ctx.closePath();
    window["clock"].appendChild(canvas);
    #clock{
      width: 250PX;
      height: 250px;
      border: 1px solid gray;
    }
    <div id="clock">
    </div>
        2
  •  0
  •   Ibu    6 年前

    你还没有设置画布的宽度和高度。注意,这些不是CSS属性,而是画布属性。

    canvas.height = 250;
    canvas.width = 250;
    

    Demo

        3
  •  0
  •   Jeremy J Starcher    6 年前

    通过尝试设置CSS属性(而不是画布属性)来扩展画布。我已经做了下面的更正。

    var canvas = document.createElement("canvas");
    canvas.height = 250;
    canvas.width = 250;
    var ctx = canvas.getContext("2d");
    ctx.beginPath();
    ctx.arc(125, 125, 70, 0, 2 * Math.PI);
    ctx.stroke()
    ctx.closePath();
    window["clock"].appendChild(canvas);
    #clock{
      width: 250PX;
      height: 250px;
      border: 1px solid gray;
    }
    <div id="clock">
    </div>
    推荐文章