Scaling a Rotated Ellipse in Canvas JS

I have a function to plot an elipse using JS canvas API.

  draw_ellipse(x, y, width, height, angle, ctx){
    ctx.ellipse(
      x,
      y,
      width,
      height,
      angle,
      0,
      2 * Math.PI)

    ctx.fill();
    ctx.stroke()
  }

Currently on the canvas I'm able to scale on the x and y axis by dragging the corners of the ellipse with the mouse. The core logic is the following.

  let x_move = (event.movementX)
  let y_move = (event.movementY)
  
  if(['right'].includes(this.ellipse_hovered_corner_key)){
    instance.width += x_move;
  }
  if(['left'].includes(this.ellipse_hovered_corner_key)){
    instance.width -= x_move;
  }
  if(['top'].includes(this.ellipse_hovered_corner_key)){
    instance.height -= y_move;
  }
  if(['bottom'].includes(this.ellipse_hovered_corner_key)){
    instance.height += y_move;
  }
  if(['top_right'].includes(this.ellipse_hovered_corner_key)){
    instance.height -= y_move;
    instance.width += x_move;
  }
  if(['top_left'].includes(this.ellipse_hovered_corner_key)){
    instance.height -= y_move;
    instance.width -= x_move;
  }
  if(['bot_right'].includes(this.ellipse_hovered_corner_key)){
    instance.height += y_move;
    instance.width += x_move;
  }
  if(['bot_left'].includes(this.ellipse_hovered_corner_key)){
    instance.height += y_move;
    instance.width -= x_move;
  }

This is working fine for a non-rotated ellipse. But any time I try to move the corners of a rotated ellipse I'm not getting the expected behaviour because the mouse drag in this case is not perfectly vertical or horizontal.

I wanted some help to figure out the way to calculate the "rotated width and height" give the x movement and y movement of the mouse.

Thanks!



Read more here: https://stackoverflow.com/questions/65076500/scaling-a-rotated-ellipse-in-canvas-js

Content Attribution

This content was originally published by Pablo Estrada at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: