HTML5 canvas drawing on background image with zoom - Javascript Canvas

Javascript examples for Canvas:image

Description

HTML5 canvas drawing on background image with zoom

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>


canvas{border:1px solid red;}
input.vrange1 {height:250px; -webkit-appearance: slider-vertical; writing-mode: bt-lr; }

      </style> 
      <script>
$(function(){//from   www.ja  v a  2  s .  c  o  m
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var PI=Math.PI;
    var PI2=PI*2;
    var cw,ch,imgW,imgH,mouseX,mouseY;
    var scaleFactor=1.00;
    $scaler=$("#scaler");
    $scaler.val(scaleFactor);
    $scaler.hide();
    var img=new Image();
    img.onload=start;
    img.src="https://www.java2s.com/style/demo/Opera.png";
    function start(){
        cw=canvas.width=imgW=img.width;
        ch=canvas.height=imgH=img.height;
        ctx.drawImage(img,0,0);
        $("#canvas").mousedown(function(e){handleMouseDown(e);});
    }
    function dot(x,y,color,radius){
        ctx.save();
        ctx.beginPath();
        ctx.arc(x,y,radius,0,PI2);
        ctx.closePath();
        ctx.fillStyle=color;
        ctx.fill();
        ctx.restore();
    }
    function draw(x,y,scale){
        ctx.clearRect(0,0,cw,ch);
        ctx.save();
        ctx.translate(x,y);
        ctx.scale(scale,scale);
        ctx.drawImage(img,-x,-y);
        ctx.restore();
        dot(x,y,"red",3);
    }
    $('#scaler').on('change', function(){
        scaleFactor=($(this).val());
        draw(mouseX,mouseY,scaleFactor);
    });
    function handleMouseDown(e){
      e.preventDefault();
      e.stopPropagation();
      if(!mouseX){
          var BB=canvas.getBoundingClientRect();
          var offsetX=BB.left;
          var offsetY=BB.top;
          mouseX=parseInt(e.clientX-offsetX);
          mouseY=parseInt(e.clientY-offsetY);
          draw(mouseX,mouseY,1.00);
          $("#instructions").text("Change the slider to zoom the map");
          $scaler.show();
      }
    }
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <h4 id="instructions">Click on the map to select a zoom-point.</h4> 
      <input type="range" class="vrange" id="scaler" value="1.00" min="0.00" max="3.00" step="0.10&quot;">
      <br> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials