how to save and remove a canvas state? - Javascript Canvas Reference

Javascript examples for Canvas Reference:clearRect

Description

how to save and remove a canvas state?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script> 
      <script type="text/javascript" src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> 
      <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"> 
      <style id="compiled-css" type="text/css">

#canvas1{/*from   ww  w . j  av  a 2 s  .  co  m*/
   border: 2px solid #000;
}
.defaultBorder {
   border: solid 1px black;
}
.bordering{
   border: #000 3px solid;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
$(document).on("click", "canvas", function(eg) {
   var thisCanvas = $(this).attr("id");
   var theCanvas = document.getElementById(thisCanvas);
   var ctx = theCanvas.getContext("2d");
   canvasSelected(thisCanvas, ctx);
});
var ctxWidth = 550;
var ctxHeight = 350;
function canvasSelected(theCanvas, ctx){
   if($("#"+theCanvas).hasClass("bordering")){
      ctx.restore();
      $("#"+theCanvas).addClass("defaultBorder");
      $("#"+theCanvas).removeClass("bordering");

      ctx.beginPath();
      ctx.clearRect(0,0,6,6);
      ctx.clearRect(ctxWidth- 6,0,6,6);
      ctx.clearRect(ctxWidth/2,0,6,6);
      ctx.clearRect(0,ctxHeight- 6,6,6);
      ctx.clearRect(ctxWidth- 6,ctxHeight- 6,6,6);
      ctx.clearRect(ctxWidth/2,ctxHeight- 6,6,6);
      ctx.clearRect(0,ctxHeight/2,6,6);
      ctx.clearRect(ctxWidth- 6,ctxHeight/2,6,6);
      $("#"+theCanvas).resizable("option", "disabled", true);
   }else{
      ctx.save();
      $("#"+theCanvas).removeClass("defaultBorder");
      $("#"+theCanvas).addClass("bordering");
      ctx.beginPath();
      ctx.fillStyle = "black";
      ctx.fillRect(0,0,6,6);
      ctx.fill();
      ctx.fillRect(ctxWidth- 6,0,6,6);
      ctx.fill();
      ctx.fillRect(ctxWidth/2,0,6,6);
      ctx.fill();
      // bottom rects..
      ctx.fillRect(0,ctxHeight- 6,6,6);
      ctx.fill();
      ctx.fillRect(ctxWidth- 6,ctxHeight- 6,6,6);
      ctx.fill();
      ctx.fillRect(ctxWidth/2,ctxHeight- 6,6,6);
      ctx.fill();
      // middle rects
      ctx.fillRect(0,ctxHeight/2,6,6);
      ctx.fill();
      ctx.fillRect(ctxWidth- 6,ctxHeight/2,6,6);
      ctx.fill();
      $("#"+theCanvas).resizable();
      $("#"+theCanvas).resizable("option", "disabled", false);
   }
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas1" width="550" height="350"></canvas>  
   </body>
</html>

Related Tutorials