Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I was answering your previous question. You should draw image on canvas using <code>drawImage</code> and then addEventListener of drag event on canvas.</p> <p><a href="http://jsfiddle.net/Aab7j/2/" rel="nofollow">jsfiddle</a></p> <pre><code>var drag, canvas, ctx; var posX = 0, posY = 0; var lastX, lastY; $(document).ready(function(){ canvas=document.getElementById("canvas"); ctx=canvas.getContext("2d"); var image=document.createElement("img"); image.onload=function(){ canvas.width = 800; canvas.height = 400; ctx.drawImage(image,posX,posY); init(); } image.src="http://peach.blender.org/wp-content/uploads/poster_rodents_big.jpg"; function init(){ canvas.addEventListener('mousedown', function(){ drag = true; lastX=null; lastY=null; }); document.addEventListener('mouseup', function(){ drag = false; }); document.addEventListener('mousemove', function(evt) { if(drag){ var mousePos = getMousePos(canvas, evt); var x = mousePos.x; var y = mousePos.y; ctx.clearRect(0,0,canvas.width,canvas.height); if(lastX &amp;&amp; lastY){ posX += x-lastX; posY += y-lastY; if(posX&gt;0) posX=0; if(posY&gt;0) posY=0; if(posX&lt;-image.width+canvas.width) posX = -image.width+canvas.width; if(posY&lt;-image.height+canvas.height) posY = -image.height+canvas.height; ctx.drawImage(image,posX,posY); } lastX=x; lastY=y; } }, false); } function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload