javascripthtml5-canvas2d-context-api

Scale canvas .arc to have different x and y radius


I am trying to create an arc function for CanvasRenderingContext2D that will allow the user to specify a horizontal and vertical radius (x and y radius). This is what I have so far:

function arc(x, y, w, h, start, stop) {
  ctx.save();
  ctx.translate(x, y);
  if (w !== h) {
    const m = w < h ? w : h;
    if(m === w) {
      ctx.scale(1, Math.min(w, h) / Math.max(w, h));
    } else {
    ctx.scale(Math.min(w, h) / Math.max(w, h), 1);
    }
  }
  ctx.beginPath();
  ctx.arc(0, 0, Math.min(w, h) / 2, start, stop);
  ctx.restore();
  ctx.fill();
  ctx.stroke();
}

I would for the arc to have the same width and height as specified by the function arguments.


Solution

  • I have found a solution. Apologies for answering my own question.

    function arc(x, y, w, h, start, stop) {
              ctx.save();
              ctx.translate(x, y);
                if (w !== h) {
                  if(w > h) {
                    ctx.scale(Math.max(w, h) / Math.min(w, h), 1);
                  } else {
                    ctx.scale(1, Math.max(w, h) / Math.min(w, h));
                  }
                }
                ctx.beginPath();
                ctx.arc(0, 0, Math.min(w, h) / 2, start, stop);
                ctx.restore();
              ctx.fill();
              ctx.stroke();
            }
    

    Essentially, I just change which direction I scale depending on which side is bigger.