Drag a Sprite Source Code

Step 4

Source code with the series of events required to drag a sprite on mobile devices and desktops. Includes device rotation, scrolling, and browser window resize events.

Drag the Sprite Example Main JavaScript drag.js Page Load JavaScript Resize All

drag.js

drag.js includes some generic JavaScript to save the location of a touch point on the canvas.

// The dimensions of the canvas:
var I_DIM = new Number(
 300
);
 
// Half the dimensions of the canvas.
var I_DIM_HALF = new Number(
 150
);

// The touch point range of
// a point on the triangle. 
// One quarter of the canvas:
var I_RANGE = null;

// Three points for a triangle:
var I_POINT_COUNT = null;

// The radius.
var I_RAD = new Number(
 36
);

// The circumference 
var CIRCUM = new Number(
 Math.PI*2
);  

// The bounding box of the canvas:
var bb;

// Array of points:
var aPoints = null;

// The most recent point selected:
var pointLast = null;

var canvas = null;

// The canvas 2d context:
var ctx = null;
 
// HTML element for debugging output:
var eDebug = null;
 
// bRun is false when not dragging,
// bRun is true when dragging the mouse
// or mobile touch point.
var bRun = false;

// If the user scrolled, we need
// to keep track of the offset.
// along the Y axis, in the browser:
// If not the offset is the top
// of the canvas. 
var dYOffset = new Number(
 0
);
var dXOffset = new Number(
 0
);

// Mobile X, Y Offsets from scrolling.
var mYOffset = new Number(
 0
); 
var mXOffset = new Number(
 0
);

// Scroll X,Y positions:
var nYScroll = new Number(
 0
);
var nXScroll = new Number(
 0
);

Load the Drag Example

/**
* function loadExample() calls
* function init() when the Web
* page loads.
*/
function init(){

 canvas = document.getElementById(
  'cv'
 );

 ctx = canvas.getContext(
  '2d'
 );

 eDebug = document.getElementById(
  "eDebug"
 );
  
resizeAll();
  
window.addEventListener(
 'scroll',
 function (e) {
  resizeHandler(e);},
 false
);  
       
window.addEventListener(
 'resize',
 function (e) {
  resizeHandler(e);
 },
 false
);  
 
drawReset();
  
// For mobile devices
// with touch events.
if ("ontouchstart" in window){

canvas.addEventListener(
'touchmove', 
function (e) 
{ 

// Prevent scrolling.   
e.preventDefault(); 


if (bRun == false) return false; 

if (e.targetTouches.length >=  1) 
{
  var t1 = e.targetTouches[0]; 
               
  pointMoveMD(
   t1.pageX - mXOffset,
   t1.pageY-mYOffset
  );

  return false;
 }

 return false;
 },false
);

canvas.addEventListener(
 'touchstart', 
 function (e) 
 {   
  e.preventDefault();
  pointStart();
  return false;
 },
 false
);

canvas.addEventListener(
 'touchend', 
 function (e) 
 {
  e.preventDefault();
  pointEnd();
  return false;
 },
 false
);  
  
if (window.DeviceOrientationEvent){   
 window.addEventListener(
  'deviceorientation', 
  function (e) 
  {
   resizeHandler(e);
  }, 
  false
 );   
}
}
  
// For desktop computers.
else {
canvas.addEventListener(
 'mousemove',
 function (event)
 {
  pointMoveD(event);
 },
 false
 );
}  
}
 
/**
* function PointXY()
* creates one PointXY() 'instance'.
* A set of PointXY() are saved
* in our Array 'aPoints'.
*/
function PointXY(n,nX,nY){
 this.idx = n;
 this.nx = nX;
 this.ny = nY;
 return this;
}
 
/**
* function pointOverTest()
* checks each point to 
* determine if the 
* touch point or mouse are 
* within range of a point.
**/
function pointOverTest(pnX,pnY){

 var p  = null;  
 for (var i= 0; i < I_POINT_COUNT; i++){
 
 p = aPoints[i];   
 
 if ((p.nx - I_RANGE) < pnX 
      && (p.nx + I_RANGE) > pnX){
  
  if ((p.ny - I_RANGE) < pnY 
      && (p.ny + I_RANGE) > pnY){     
   return p;     
  }
 } 
} 
return null;  
}

/**
* function pointStart() 
* Starts moving the point
* in response to touchstart and
* onmousedown events.
* Function called by the touchstart event.
* Handler for the onmousedown event.
**/ 
function pointStart(){

// Set pointLast to null.
// Code will find a new point.
 pointLast = null;
 bRun = true;
 
}

Stop Interactive Movement

/**
* function pointEnd() 
* Stops moving the point
* in response to touchend and
* onmouseup events.
* Function called by the touchend event.
* Handler for the onmouseup event.
**/ 
function pointEnd(){
// Set pointLast to null.
// Code will find a new point.  
pointLast = null;
bRun = false;
}

/**
* function pointMoveD()
* moves the point on desktops.
* Handler for the onmousemove event.
**/
function pointMoveD(event){  
if (bRun == false) return;
var pX = event.clientX - dXOffset;
var pY = event.clientY - dYOffset; 
pointMoveMD(pX,pY);
} 
/**
* Save offsets for
* mobile and desktop
* browsers.
*/
function resizeAll(){
  
mYOffset = 0;

mXOffset = 0;

if (canvas != null){

 bb = canvas.getBoundingClientRect();


 dYOffset = Math.floor(
  bb.top
 );

 // The X offset is bb.left.
 dXOffset = Math.floor(
  bb.left
 );

 nYScroll = 0;

 nXScroll = 0;

}
  
// For desktops subtract the 
// scroll position from the 
// top of the canvas.
// Only if the offset with 
// the range check will
// not be negative.
if (bb != null){
if (window.pageYOffset != null){

 nYScroll = window.pageYOffset;
         
}
if (window.pageXOffset != null){

 nXScroll = window.pageXOffset;
        
}
   
if (bb.top > 0){

 mYOffset = bb.top + nYScroll;
 
}
else if (nYScroll > 0){

 // Add a negative to subract.
 mYOffset = nYScroll + bb.top;
 
}

if (bb.left > 0){

mXOffset = bb.left + nXScroll;

}
else if (nXScroll > 0){

// Add a negative to subract.
 mXOffset = nXScroll + bb.left;
 
}
   
} 
 
drawReset(); 

}
 
/**
* If the window is scrolled, 
* resized, or rotated, 
* obtain X and Y offsets. 
* of the canvas.
**/
function resizeHandler(e){
 e.preventDefault();
 resizeAll();  
 return false; 
} 	

Page Load JavaScript

The Drag a Sprite example draws one point on the Web page. Function loadExample() executes when the Drag a Sprite Web page loads. Function loadExample() calls into JavaScript functions from drag.js to obtain canvas coordinates.

/**
* Called when the page loads.
*/
function loadExample(){
 I_RANGE = new Number(75);
 I_POINT_COUNT = new Number(1);
  
 // Call drag.js 
 // function init().
 init();
}

/*
* Resets the point
* to the center.
*/
function drawReset(){

pointLast = new PointXY(
 0,
 I_DIM_HALF,
 I_DIM_HALF
);

aPoints = new Array(pointLast);

pointDraw();  
}

/*
* Moves the point
* for desktop and mobile
* devices.
* Called from drag.js.
*/
function pointMoveMD(nX,nY){
 
var p = pointOverTest(
 nX,
 nY
);

if (p != null){
pointLast = new PointXY(
 0,
 nX,
 nY
);

aPoints[0] = pointLast;

pointDraw(); 

pointLast = null;   
}    
}

/*
* Draws the point.
*/
function pointDraw(){
 
ctx.beginPath();

ctx.fillStyle = "black";

ctx.fillRect(
0,
0,
I_DIM,
I_DIM
);

ctx.fillStyle = "blue";

ctx.arc(
 pointLast.nx,
 pointLast.ny,
 I_RAD,
 0,
 CIRCUM
); 
   
ctx.fill();  
}

Step 4

Tags

drag and drop, draggable js, JavaScript, javascript move element, click and drag, drag event, html5, learn to code, codes, coding, how to code, STEM, stem projects, webcourses, website design, web developer, tutorial, free tutorial,
Learn 3D Programming Learn 3D Programming
Copyright © 2015 Seven Thunder Software. All Rights Reserved.