G
G
Gaida7772017-09-25 11:34:06
css
Gaida777, 2017-09-25 11:34:06

Why is it crooked when converting radians to degrees when drawing a circle on canvas?

When drawing a circle through setInterval - the circle is not drawn clearly. What is the jamb?

<canvas class="canvas"></canvas>
  <div class="btn"></div>
  <style>

  .canvas{
    width: 600px;
    height: 300px;
    background: #fff;
  }
  .btn{
    width: 100px;
    height: 50px;
    background: red;
  }
  </style>
  <script>
  var btn = document.querySelector('.btn');
  var canvas = document.querySelector('.canvas');
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;

      var centerY = canvas.height / 2;
      var radius = 30;
      function getRadians(degrees) {
  return (Math.PI/180)*degrees;
}
  var degrees = 0;
function foo(){
  var setInterval_1 = setInterval(
    function (){
      
      if(degrees<=360){
      context.beginPath();
      context.arc(centerX, centerY, radius, 0, getRadians(degrees), false);
      context.lineWidth = 1;
      context.fill
      context.strokeStyle = '#003300';
      context.stroke();
      degrees+= 1;
      btn.innerHTML = Math.floor(degrees/360*100) + "%";
  		}
      
      },
      5);
  
  degrees = 0;
  context.clearRect(0, 0, canvas.width, canvas.height);
}

  btn.addEventListener("click", foo);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Eugene Chefranov, 2019-06-12
@Arhangel_one

As an option

D
DTX, 2017-09-25
@DirecTwiX

You need to specify a resolution for the canvas. The default is 300x150

<canvas class="canvas" width="600px" height="300px"></canvas>

P
Pavel Kornilov, 2017-09-25
@KorniloFF

<canvas class="canvas"></canvas>
  <div id="btn"></div>
  <style>

  .canvas{
  width: 600px;
  height: 300px;
  background: #fff;
  }
  .canvas+#btn{
  width: 100px;
  height: 50px;
  background: red;
  }
  </style>

  <script>
  'use strict';
  var canvas = document.querySelector('.canvas'),
  	btn = document.querySelector('.canvas+#btn'),
  context = canvas.getContext('2d'),
  centerX = canvas.width / 2;

    var centerY = canvas.height / 2;
    var radius = 30;
  function getRadians(degrees) {
    return (Math.PI/180)*degrees;
  }


function foo() {
  var degrees = 0;
 	var setInterval_1 = setInterval( function () {
 		if(degrees>=360) clearInterval(setInterval_1);
 		context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.arc(centerX, centerY, radius, 0, getRadians(degrees), false);
    context.lineWidth = 2;
    context.strokeStyle = '#003300';
    context.stroke();
    degrees+= 5;
    btn.innerHTML = Math.floor(degrees/360*100) + "%";

  }, 10);

}

  btn.addEventListener("click", foo);
  </script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question