title: Html canvas rotate larger image with aspect ratio
body: <p>I have a code sample where I am adjusting a large image to a smaller size with the canvas matching the size of the image. There is a rotate right functionality that will rotate the image inside of the canvas which will adjust the canvas size. I almost have it perfectly working but the image is perfect size only when original or upside down. I can't get the height to be right ratio when the image is rotated on left or right. Here is my jsfiddle and code which is modified code from a different fiddle. Image is just used as test.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas=document.getElementById("canvas");
      var ctx=canvas.getContext("2d");
      var canvasWidth = 400;
      var canvasHeight;
  
      var degrees=0;
  
      var image=document.createElement("img");
      image.onload=function(){
      canvas.width = canvasWidth;
      canvasHeight = 400 / (image.width / image.height);  
      canvas.height = canvasHeight;
      ctx.drawImage(image,0,0,canvas.width,canvas.height);
      }
    
  
      image.src="https://www.magezinepublishing.com/equipment/images/equipment/Lumix-DMCFZ330-5824/highres/Panasonic-Lumix-FZ330-Wide-P1010001_1438873612.jpg";
  
  
       $("#clockwise").click(function(){
       degrees+=90
       if (degrees &gt;= 360) degrees = 0;
       
       if (degrees === 0 || degrees === 180 ) {
           canvas.width = canvasWidth;
           canvas.height = canvasHeight;
       }
       else {
           // swap
           canvas.width = canvasHeight;
           canvas.height = canvasWidth;
       }
       ctx.save();
       // you want to rotate around center of canvas
       ctx.translate(canvas.width/2,canvas.height/2);
      
       ctx.rotate(degrees*Math.PI/180);
       ctx.drawImage(image, -canvas.width*0.5, -canvas.height*0.5, canvas.width, canvas.height);
       ctx.restore();
      });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;canvas id="canvas" &gt;&lt;/canvas&gt;&lt;br&gt;
      &lt;button id="clockwise"&gt;Rotate right&lt;/button&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><a href="https://jsfiddle.net/xarnvbdw/6/" rel="nofollow noreferrer">jsfiddle</a></p>
  
  <p>Any help is appreciated.</p>