HTML5 Panning based on Mouse Movement - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

HTML5 Panning based on Mouse Movement

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.6.2.js"></script> 
      <style id="compiled-css" type="text/css">

canvas { border: 2px solid black; height: 637px; width: 932px; }


      </style> 
      <script type="text/javascript">
    $(window).load(function(){//www . j a  v a 2  s.c  om
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mouse = {x: 0, y: 0}; //make an object to hold mouse position
var startCoords = {x: 0, y: 0};
var last = {x: 0, y: 0};
var isDown = false;
var scale = 2;
var img = new Image();
img.src = "https://www.java2s.com/style/demo/Google-Chrome.png";
function render() {
    'use strict';
    ctx.beginPath();
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.fillRect(0, 0, canvas.width, canvas.height); 
    ctx.arc(mouse.x, mouse.y, 250, 0, 6.28, false);//draw the circle
    ctx.restore();
    ctx.save();
    ctx.clip();
    ctx.drawImage(img, 0, 0,
                  img.width * scale, img.height * scale);
    ctx.closePath();
    ctx.restore();
}
setInterval(render, 100);// set the animation into motion
canvas.onmousemove = function (e) {
    'use strict';
    var xVal = e.pageX - this.offsetLeft,
        yVal = e.pageY - this.offsetTop;
    mouse = {x: e.pageX,
             y: e.pageY};
    if (isDown) {
        ctx.setTransform(1, 0, 0, 1,
                         xVal - startCoords.x,
                         yVal - startCoords.y);
    }
};
canvas.onmousedown = function (e) {
    'use strict';
    isDown = true;
    startCoords = {x: e.pageX - this.offsetLeft - last.x,
                   y: e.pageY - this.offsetTop - last.y};
};
canvas.onmouseup   = function (e) {
    'use strict';
    isDown = false;
    last = {x: e.pageX - this.offsetLeft - startCoords.x,
            y: e.pageY - this.offsetTop - startCoords.y};
};
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" height="637" width="932"></canvas>  
   </body>
</html>

Related Tutorials