Tamás
Tamás

Reputation: 1112

Run a circle through the points of a quadric curve with JavaScript and Canvas

I want to run a circle through every point of a quadric curve because I'm making a circle-throw game. This is an example code of my problem:

canvas.width = 200;
canvas.height = 200;
ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.quadraticCurveTo(20,200,200,200);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "orange";
ctx.arc(20,20,20,Math.PI*2,0);
ctx.fill();
function loop(){
  //Code to move circle through the quadric curve
  //???
  //???
  ctx.beginPath();
  ctx.fillStyle = "orange";
  ctx.arc(20,20,20,Math.PI*2,0);
  ctx.fill();
  requestAnimationFrame(loop);
}
*{
  margin: 0;
  padding: 0;
}
   <canvas id="canvas"></canvas> Run that circle through the curve

How can I solve this?
Sorry for my English and thanks for the answers!

Upvotes: 0

Views: 247

Answers (1)

Rodrigo5244
Rodrigo5244

Reputation: 5545

You need to code the parametric formula for the quadratic curve given below to get the points of the curve.

quadratic Bezier formula

This formula gives the points of the curve in terms of three other points and t.

The first point is where the path begins before the call to quadraticCurveTo, the other two points are the points passed to quadraticCurveTo.

You change the value of t to get different points of the curve, when t is 0 you get the first point and when t is 1 you get the last point, values between 0 and 1 are going to give you points in the middle of the curve.

You can also get the points of the curve by drawing the curve using quadraticCurveTo and check the colours of the pixels with getImageData.

Upvotes: 0

Related Questions