title: How to re-calculate Image size in Canvas after rotation?
body: <p>Here's a fiddle of my project!</p>
  <p><a href="https://jsfiddle.net/aL985q7r/1/#run" rel="nofollow noreferrer">https://jsfiddle.net/aL985q7r/1/#run</a></p>
  <p>I dont want the <strong>Canvas's context</strong> to get outside of the <strong>Canvas</strong> when I drag it.And its working until I rotate the Image.</p>
  <p>Then whenever I get close one of the Canvas's sides the Image not keeping the rotated state and instead and draw the Image without rotation.</p>
  <p><strong>So how to prevent the Image to get outside the Canvas and also keep there rotation?</strong></p>
  <p>Like in its normal none rotated state...</p>
  <p>(The code might be a bit &quot;Spagetti&quot;,I'm sorry about that its not finished)</p>
  <p>Any help appreciated!
  Thank you!</p>
  <pre><code>function domElement(){
  
      let canvas,ctx,X,Y,scaleX,scaleY,angle;
      let conta;
      let paint,paint2,paint3,paint4,paint5;
      let d,d2,d3,d4,d5;                          //Distances for grabbing the Image at certain points
      let size,rotation,imagestyle;                //Buttons
      let addP=10;                                //A number that divide the Image original size
      let roTate=0;                               //Set initial rotation value for the rotationBar2
  
  
      
      conta = document.createElement(&quot;div&quot;);  //Create a container for the Canvas
      canvas = document.createElement(&quot;canvas&quot;);  //Create Canvas
      ctx = canvas.getContext(&quot;2d&quot;);      //Canvas context
  
      let btnArray =[                 //Dynamically assign Id's and innerText's for Buttons
          {btnId:&quot;additionBtn&quot;,
           btnText:&quot;Size&quot;},
  
          {btnId:&quot;rotationBtn&quot;,
           btnText:&quot;Rotation&quot;},
  
          {btnId:&quot;imageStyle&quot;,
          btnText:&quot;ImageStyle&quot;}
      ];
  
      let flexCont = document.createElement(&quot;div&quot;);      //Create a Flex container for the Buttons
      flexCont.id=&quot;btnCont&quot;;
      conta.appendChild(flexCont);
  
      btnArray.forEach((val)=&gt;{
  
          let btn0=document.createElement(&quot;btn&quot;);
          btn0.id=val[&quot;btnId&quot;];
          btn0.className=&quot;flexBtn&quot;;
          btn0.innerText = val[&quot;btnText&quot;];
          flexCont.appendChild(btn0);
  
      });
  
      document.body.appendChild(conta); //Append the main Container to the body
      conta.appendChild(canvas);
  
      
  
  
  image = new Image();        //Create an image Object
  image.src=&quot;./1.png&quot;;        //Assign any src for it
  
  
  function firstInit(img,x,y,scalex,scaley){
      image.width = scaleX;
      image.height = scaleY;
  
      scaleX = scalex;
      scaleY = scaley;
  
      X=x;
      Y=y;
      ctx.drawImage(img,x,y,scaleX,scaleY);
  }
  
  image.onload = ()=&gt;{
  firstInit(image,canvas.clientWidth/2,canvas.clientHeight/2,image.naturalWidth/addP,image.naturalHeight/addP);
  
  };          //Initialized image when ready
  
  function go(){
  
      function distanceMeasure(e){        //Calculating distance for 5 different points where the Image is draggable
  
          let a = e.offsetX -(X+scaleX/2);
          let b = e.offsetY -(Y+scaleY/2);
  
          let a2 = e.offsetX -(X+scaleX/5);
          let b2 = e.offsetY -(Y+scaleY/5);
  
          let a3 = e.offsetX -(X+scaleX);
          let b3 = e.offsetY -(Y+scaleY);
  
          let a4 = e.offsetX -(X+scaleX);
          let b4 = e.offsetY -(Y+scaleY/5);
  
          let a5 = e.offsetX -(X+scaleX/5);
          let b5 = e.offsetY -(Y+scaleY);
  
          let distance = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
          d=distance;
  
          let distance2 = Math.sqrt(Math.pow(a2,2)+Math.pow(b2,2));
          d2=distance2;
  
          let distance3 = Math.sqrt(Math.pow(a3,2)+Math.pow(b3,2));
          d3=distance3;
  
          let distance4 = Math.sqrt(Math.pow(a4,2)+Math.pow(b4,2));
          d4=distance4;
  
          let distance5 = Math.sqrt(Math.pow(a5,2)+Math.pow(b5,2));
          d5=distance5;
      }
  
  
      canvas.addEventListener(&quot;mousedown&quot;,(e)=&gt;{      //If its within distance allow drag (paint true)
  
          distanceMeasure(e);
  
          if(d &lt; (scaleX-scaleY)/2 ){
              console.log(&quot;moveable&quot;);
              paint =true;
          }
        
          else if(d2 &lt; (scaleX-scaleY)/2){
              console.log(&quot;moveable&quot;);
              paint2 =true;
          }
  
          else if(d3 &lt; (scaleX-scaleY)/2){
              console.log(&quot;moveable&quot;);
              paint3 =true;
          }
  
          else if(d4 &lt; (scaleX-scaleY)/2){
              console.log(&quot;moveable&quot;);
              paint4 =true;
          }
  
          else if(d5 &lt; (scaleX-scaleY)/2){
              console.log(&quot;moveable&quot;);
              paint5 =true;
          }
  
      });
  
      canvas.addEventListener(&quot;mousemove&quot;,(e)=&gt;{      
      
          if(X+scaleX &lt; canvas.width || Y+scaleY &lt; canvas.height || X &gt; 0 || Y &gt; 0){      //If its within Canvas range and one of the paint is true then drawImage or rotated Image
  
          if(paint){
  
              X = e.offsetX-scaleX/2;
              Y = e.offsetY-scaleY/2;
  
              if(angle != null){
                  angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
              }
  
              else{
   
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,Y,scaleX,scaleY);      
          }   
    }
  
  
          else if(paint2){
  
              X = e.offsetX-scaleX/5;
              Y = e.offsetY-scaleY/5;
  
              if(angle != null){
                  angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
              }
  
              else{
   
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,Y,scaleX,scaleY);      
          }  
  }
  
  
          else if(paint3){
  
              X = e.offsetX-scaleX/1.1;
              Y = e.offsetY-scaleY/1.1;
  
              if(angle != null){
                  angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
              }
  
              else{
   
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,Y,scaleX,scaleY);      
          }  
  }
  
  
          else if(paint4){
  
              X = e.offsetX-scaleX/1.1;
              Y = e.offsetY-scaleY/5;
  
              if(angle != null){
                  angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
              }
  
              else{
   
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,Y,scaleX,scaleY);      
          }  
  }
  
  
          else if(paint5){
  
              X = e.offsetX-scaleX/5;
              Y = e.offsetY-scaleY/1.1;
  
              if(angle != null){
  
                  angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
              }
  
              else{
   
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,Y,scaleX,scaleY);      
          }  
   }
  
  
   }
  
         if(X &lt; 0){       // These prevents the Image to clip through at the edges of the Canvas
  
          ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
          ctx.drawImage(image,0,Y,scaleX,scaleY); 
  
          }
  
          else if(Y &lt; 0 ){
           
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,0,scaleX,scaleY); 
          }
  
          if(X+scaleX &gt; canvas.width){
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,canvas.width-scaleX,Y,scaleX,scaleY);
          }
  
          else if(Y+scaleY &gt; canvas.height){
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,X,canvas.height-scaleY,scaleX,scaleY);
          }
  
          else if(X &lt; 0 &amp;&amp; Y&lt; 0){
              
              ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
              ctx.drawImage(image,0,0,scaleX,scaleY); 
          }
  
      if(X &lt; 0 &amp;&amp; Y+scaleY &gt; canvas.height){
          ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
          ctx.drawImage(image,0,canvas.height-scaleY,scaleX,scaleY); 
      }
  
      else if(X+scaleX &gt; canvas.width &amp;&amp; Y &lt; 0){
          ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
          ctx.drawImage(image,canvas.width-scaleX,0,scaleX,scaleY); 
      }
  
      else if(X+scaleX &gt; canvas.width &amp;&amp; Y+scaleY &gt; canvas.height){
          ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
          ctx.drawImage(image,canvas.width-scaleX,canvas.height-scaleY,scaleX,scaleY); 
      }
  
     
       });
  
       canvas.addEventListener(&quot;mouseup&quot;,(e)=&gt;{       //When let the mouse set paint to false
         
          paint=false;
          paint2=false;
          paint3=false;
          paint4=false;
          paint5=false;
         
       });
  
       canvas.addEventListener(&quot;mouseleave&quot;,()=&gt;{         //When mouse leave the canvas's area set paint to false
  
          paint=false;
          paint2=false;
          paint3=false;
          paint4=false;
          paint5=false;
       });
  
  
      
     
  }
  
  window.addEventListener(&quot;resize&quot;,(e)=&gt;{         //Resize everything based on the Window.innerWidth and innerHeight
  
      let conta = document.getElementById(&quot;conta&quot;);
      
      canvas.width = window.innerWidth/2;
      canvas.height = window.innerHeight/2;
      
      firstInit(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
  
      conta.style.width =(canvas.width+canvas.width/12)+&quot;px&quot;;
      conta.style.height =(canvas.height+canvas.width/12)+&quot;px&quot;;
  
  })
  
  function domStyle(){        //Created this function to not all the code be in the same place...Kind of
  
      let z = false;              // Preventing to create multiple range bars
  
      size=document.getElementById(&quot;additionBtn&quot;);        //Resize button
      rotation=document.getElementById(&quot;rotationBtn&quot;);        // Rotation button
      imagestyle = document.getElementById(&quot;imageStyle&quot;);         //Image style ( not functioning yet )
  
      let cssLink = document.createElement(&quot;link&quot;);              //Create link for CSS and append it to the Head
      cssLink.rel =&quot;stylesheet&quot;;
      cssLink.href =&quot;./index.css&quot;;
      document.head.appendChild(cssLink);
  
      canvas.id=&quot;canvas&quot;;
      canvas.width = window.innerWidth/2;
      canvas.height = window.innerHeight/2;
  
      conta.id=&quot;conta&quot;;                                               //Set the Canvas parent container to canvas size + some more (Not good solution,change later...)
      conta.style.width =(canvas.width+canvas.width/12)+&quot;px&quot;;
      conta.style.height =(canvas.height+canvas.height/12)+&quot;px&quot;;
  
      size.addEventListener(&quot;click&quot;,()=&gt;{         //When clicked create a range bar to set the Context size
       
          sessionStorage.setItem(&quot;btn1clicked&quot;,true);         //To check if the size buton clicked
          size.classList.add(&quot;highlight&quot;);            //Highlight the choosed action
  
          if(sessionStorage.getItem(&quot;btn2clicked&quot;) || sessionStorage.getItem(&quot;btn3clicked&quot;)){
  
              sessionStorage.removeItem(&quot;btn2clicked&quot;);       //If you used another action before remove those Click checks
              sessionStorage.removeItem(&quot;btn3clicked&quot;);
              rotation.classList.remove(&quot;highlight&quot;);         //Remove its highlight class
  
              z=false;            //Set z to false so the Buttons can create range bars again
  
  
              let range = document.getElementById(&quot;sizeBar&quot;); 
              if(range != null){
                  range.parentElement.removeChild(range);         //Remove range bar from the Body
              }
             
          }
  
  
          if(sessionStorage.getItem(&quot;btn1clicked&quot;) &amp;&amp; z == false ){       //Creating the range bar
  
          z = true;
          let rangeBar = document.createElement(&quot;input&quot;); 
          rangeBar.type=&quot;range&quot;;
          rangeBar.name=&quot;range&quot;;
          rangeBar.min=1;
          rangeBar.max = 20;
          rangeBar.value =addP;
          rangeBar.id=&quot;sizeBar&quot;;
          conta.appendChild(rangeBar);
  
          let range = document.getElementById(&quot;sizeBar&quot;);
  
          range.addEventListener(&quot;input&quot;,()=&gt;{        //If the range value changes set addP higher or lower to Decrease or Increased the Context size
              
                  addP=range.value;
  
                  if(angle != null){
                      angle(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
                  }
  
                  else {
                      ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
                      firstInit(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP)
                  }
                 
          })
  
      };
  
      });
  
      rotation.addEventListener(&quot;click&quot;,()=&gt;{              
  
          rotation.classList.add(&quot;highlight&quot;);        //Highlight the choosed action
          sessionStorage.setItem(&quot;btn2clicked&quot;,true);     //To check if the rotation buton clicked 
  
          if(sessionStorage.getItem(&quot;btn1clicked&quot;) || sessionStorage.getItem(&quot;btn3clicked&quot;)){
  
              sessionStorage.removeItem(&quot;btn1clicked&quot;,false);     //If you used another action before remove those Click checks
              sessionStorage.removeItem(&quot;btn3clicked&quot;,false);
              size.classList.remove(&quot;highlight&quot;);                 //Remove its highlight class
              z=false;                                //Set z to false so the Buttons can create range bars again
  
              let range = document.getElementById(&quot;sizeBar&quot;);
              if(range != null){
                  range.parentElement.removeChild(range);     //Remove range bar from the Body
              }
                 
          }    
      
  
          if(sessionStorage.getItem(&quot;btn2clicked&quot;) &amp;&amp; z == false){        //Creating the range bar
  
          z=true; 
          let rangeBar2 = document.createElement(&quot;input&quot;);
          rangeBar2.type=&quot;range&quot;;
          rangeBar2.name =&quot;range&quot;;
          rangeBar2.id=&quot;sizeBar&quot;;
          rangeBar2.min = -360;
          rangeBar2.max = 360;
          rangeBar2.value = roTate; 
  
          conta.appendChild(rangeBar2);
          
          rangeBar2.addEventListener(&quot;input&quot;,()=&gt;{        //If the range value changes set roTate and rotate the Context Clockwise or CounterClockwise
             
             roTate = rangeBar2.value;
             function rotation (img,xs,ys,wide,tall){                 //Rotation function
  
             let a= Math.sqrt(Math.pow((canvas.width-canvas.width)-(X+scaleX/2),2));      //Set the rotation center to the image center
             let b = Math.sqrt(Math.pow((canvas.height-canvas.height) -(Y+scaleY/2),2));
  
             ctx.save();                      //Rotation method
             ctx.translate(a,b);
             ctx.rotate(Math.PI*rangeBar2.value/180);
             ctx.translate(-(a),-(b));
             ctx.clearRect(0,0,canvas.clientWidth,canvas.clientHeight);
             firstInit(img,xs,ys,wide,tall)
             ctx.restore();
            
          }
          
          rotation(image,X,Y,image.naturalWidth/addP,image.naturalHeight/addP);
          angle=rotation;             //Set the angle.If angle != null,then instead of first init this will run
                  
          })
      }
  
  });
  
      /*
      imagestyle.addEventListener(&quot;click&quot;,()=&gt;{
  
      });
  */
  }
  
  
  domStyle();
  go()
  };
  
  
  
  let btn = document.getElementById(&quot;btn&quot;);       //When clicked call everything above
  btn.addEventListener(&quot;click&quot;,()=&gt;{
      domElement();
      
  })
  </code></pre>