Restore div background color to original when mouseout with background image - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Restore div background color to original when mouseout with background image

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Canvas to copy part of the image</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-git.js"></script> 
      <style id="compiled-css" type="text/css">

.wrapper {//from  w ww. j a va  2s  . c om
   position: relative;
   width: 678px;
   height: 900px;
   background:#003344;
}
.wrapper .box {
   display: inline-block;
   position: relative;
   width: 221px;
   height: 221px;
   border: solid 1px #333;
}


      </style> 
   </head> 
   <body> 
      <div class="wrapper"> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
         <div class="box"></div> 
      </div> 
      <canvas id="canvas" width="223" height="223" style="display: none;">
          This text is displayed if your browser does not support HTML5 Canvas. 
      </canvas> 
      <img id="imgloader" crossOrigin="anonymous" style="display: none;"> 
      <script type="text/javascript">
var canvas = null;
var ctx = null;
var img_loader = null;
function initCanvas() {
  canvas = document.getElementById('canvas');
  canvas.width = 221;
  canvas.heigth = 221;
  ctx = canvas.getContext("2d");
  img_loader = document.getElementById('imgloader');
  var bg = 'https://www.java2s.com/style/demo/Google-Chrome.png';
  img_loader.src = bg;
}
$(document).ready(function(){
   initCanvas();
  $('.box').hover(function() {
     $(this).css('background-color', 'red');
     $(this).css('background-image', 'none');
  }, function () {
     var pos = $(this).position();
 ctx.drawImage(img_loader,pos.left,pos.top,canvas.width, canvas.height,0,0,canvas.width, canvas.height);
     $(this).css('background-color','transparent' );
     $(this).css('background-image','url(' + canvas.toDataURL() + ')' );
  });
})

      </script>  
   </body>
</html>

Related Tutorials