0

I want to build an analog clock using a canvas. The first step is to draw a circle but for some reason the circle is not being correctly drawn. The circle is not complete. This is what I'm trying to do:

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>

I am trying really hard to understand why the circle is not being drawn properly. I need this to be dynamic though. How can I make this work?

halfer
  • 19,824
  • 17
  • 99
  • 186
Morfinismo
  • 4,985
  • 4
  • 19
  • 36

3 Answers3

3

You need to set canvas width and height attributes properly. Now you are using defaults (300x150) and stretching that to a square. That is why your image appears skewed.

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>
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26
0

You haven't set the width and height of the canvas. Note that these are not CSS properties but canvas properties.

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

Demo

Ibu
  • 42,752
  • 13
  • 76
  • 103
0

You are making your canvas stretch out by trying to set the CSS properties, but not the canvas properties. I've made the corrections below.

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>
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74