Toniq Toniq - 2 months ago 19
CSS Question

Css canvas circle stroke sharpness

I have a circle seekbar on my audio player which draws canvas circle in timer interval.

The problem is that as canvas gets redrawn it looses it sharpness.

This be be seen here (canvas drawn only once):

https://jsfiddle.net/0zs2gqxk/

Here its redrawn 50 times for simulation:

https://jsfiddle.net/4bf9ka49/

You can see how in second example edges get ugly.

Is there a way to avoid that?

<canvas id="myCanvas" width="578" height="200"></canvas>

Answer

Add context.clearRect(0, 0, canvas.width, canvas.height) to you code to clear the canvas, so it won't make multiple in the same spot.

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;

for (var i = 0; i < 50; i++) {

  context.clearRect(0, 0, canvas.width, canvas.height);

  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

  context.lineWidth = 5;
  context.strokeStyle = '#0000ff';
  context.stroke();
  context.clearRect(0, 0, canvas.width, canvas.height);
}

Here's a image of the first JSFiddle you shared, and my code's image. JSFiddle

My Code

Identical.

Comments