JSFiddle - React, Tailwind, and code Playground

by anubhabB

HTML

<button id="rotate">Rotate 15deg</button>
<canvas width="95" height="95" id="cnv"></canvas>
<canvas width="95" height="95" id="cnv2"></canvas>

<canvas width="95" height="95" id="cnvSampl" hidden></canvas>

CSS

#cnv,#cnv2{
    border:1px solid #ccc
}

JavaScript

var cntx = document.getElementById('cnvSampl').getContext('2d');
cntx.fillStyle = '#fc0';
cntx.fillRect(0,0,95,95);
var canv = document.getElementById('cnv');
var ctx  = canv.getContext('2d');
var canv2= document.getElementById('cnv2');
var ctx2  = canv2.getContext('2d');

var img = new Image();
var imgW, imgH;
var translateX, translateY;
var axisFactor = 2;
var rot = 0;

function rotate(){
    rot++;
    //This is without resize
    translateX = cnv.width/axisFactor;
    translateY = cnv.height/axisFactor
    ctx.clearRect(0,0,imgW,imgH);
    ctx.save();
    ctx.translate(translateX,translateY);
    ctx.rotate(15*rot*0.0174532925);
    ctx.drawImage(img,-translateX,-translateY);
    ctx.restore();
    //Resizing Canvas - this part is creating problem
    var w = imgW;
    var h = imgH;
    
    var newWidth,newHeight;
    var c = Math.cos(15*rot*0.0174532925);
    var s = Math.sin(15*rot*0.0174532925);
    
    if (s < 0) { s = -s; }
    if (c < 0) { c = -c; }
    newWidth = h * s + w * c;
    newHeight = h * c + w * s ;
    
    cnv2.width = newWidth;
    cnv2.height= newHeight;
    
    translateX = cnv2.width/axisFactor;
    translateY = cnv2.height/axisFactor
    ctx2.clearRect(0,0,cnv2.width,cnv2.height);
    ctx2.save();
    ctx2.translate(translateX,translateY);
    ctx2.rotate(15*rot*0.0174532925);
    ctx2.drawImage(img,-translateX,-translateY);
    ctx2.restore();
}

function init(){
    img.onload = function(){
        imgW = img.width;
        imgH = img.height;
        ctx.drawImage(img,0,0,imgW,imgH);
        ctx2.drawImage(img,0,0,imgW,imgH);
    }
    img.src = document.getElementById('cnvSampl').toDataURL();
    document.getElementById('rotate').onclick = function(){
         rotate(); 
    };
}
init();