Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want my canvas draw a circle but result in a eclipse [duplicate]

Here is my jsfiddle:jsfiddle

I can't figure out why this code result in a eclipse, please take a look my code below, this is an animation using requestAnimationFrame.

function circleGraph(radius) {
  return {
    type: 'circle',
    radius: radius,
    currentAngleAnimate: 0
  }
}
$(document).ready(function () {
  var canvas = document.getElementById('mycanvas');
  var context = canvas.getContext('2d')
  var width = canvas.width;
  var height = canvas.height;
  var circleObj = circleGraph(50);

  context.lineWidth = 1;
  context.strokeStyle = '#ad2323';
  context.fillStyle = '#ad2323';

  var draw = function () {
    context.clearRect(0, 0, width, height);
    context.beginPath();
    circleObj.currentAngleAnimate += Math.PI * 2 / 60;
    context.arc(width / 2, height / 2, circleObj.radius, -Math.PI / 2, circleObj.currentAngleAnimate, false);
    context.stroke();
    context.lineTo(width / 2, height / 2);
    context.fill();
    requestAnimationFrame(draw)
  }
  requestAnimationFrame(draw);
});
like image 974
zl2003cn Avatar asked Nov 27 '25 07:11

zl2003cn


2 Answers

Your canvas has a default width and height of 300 x 150 pixel. Those are the attributes of the canvas HTML element. You then stretch the canvas via CSS rules to 400 x 400 pixel - however, the CSS rules only affect how the canvas is displayed, not the resolution of the canvas.

Solution: Remove your CSS and set the width and height attributes:

<canvas id="mycanvas" width="400" height="400></canvas>
like image 133
le_m Avatar answered Nov 29 '25 20:11

le_m


Remove height and width from your CSS rule:

#mycanvas {
  border: thin solid green;
  position: relative;
}

Now, add width and height through html attributes and it should work:

<canvas id="mycanvas" height="400" width="400"></canvas>
like image 23
Mohit Bhardwaj Avatar answered Nov 29 '25 19:11

Mohit Bhardwaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!