Canvas How to - Overlap cards with hidden canvas








Question

We would like to know how to overlap cards with hidden canvas.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){<!--  w w  w  . j  a  v  a  2  s  .co  m-->
    var canvas = document.getElementById('mycanvas');
    var ctx = canvas.getContext('2d');
    //use a hidden canvas
    var hidden = document.createElement('canvas');
    hidden.width = 400;
    hidden.height = 400;
    var hiddenCtx = hidden.getContext('2d');
    hiddenCtx.strokeStyle = 'blue';
    hiddenCtx.fillStyle = 'yellow';
    hiddenCtx.lineWidth = 5;
    //translate origin to centre of hidden canvas, and draw 3/4 of the image
    hiddenCtx.translate(200,200);
    for(var i=0; i<3; i++){
        hiddenCtx.fillRect(-170, -150, 300, 120);
        hiddenCtx.strokeRect(-170, -150, 300, 120);
        hiddenCtx.rotate(90*(Math.PI/180));
    }
    //reset the hidden canvas to original status
    hiddenCtx.rotate(90*(Math.PI/180));
    hiddenCtx.translate(-200,-200);
    //translate to middle of visible canvas
    ctx.translate(200, 200);
    //repeat trick, this time copying from hidden to visible canvas
    ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
    ctx.rotate(180*(Math.PI/180));
    ctx.drawImage(hidden, 200, 0, 200, 400, 0, -200, 200, 400);
}//]]>  
</script>
</head>
<body>
  <canvas id="mycanvas" width="400px" height="400px"></canvas>
</body>
</html>

The code above is rendered as follows: