Tuesday, February 18, 2014

Drag and Drop Game With html5 & javascript


In this post i am going to teach how to create a Drag & Drop Game with Html5 and javaScript. It is very easy and Quite Interesting to create so i stop talking get started
Drag and Drop Game

Download Script View Demo 

html

html is super easy one thing to keep in mind is that the element you wanted to be draggable should be set as draggable="true"

<img src="./salman.png">
<img draggable="true" src="./shirt1.png" style="top:30px; position: absolute;z-index:5px;">
<img draggable="true" src="./shirt2.png" style="top:240px; position: absolute; left:600px;absolute;z-index:5px;">
<img draggable="true" src="./shirt3.png" style="top:240px; position: absolute;absolute;z-index:5px;"> 
<img draggable="true" src="./shirt4.png" style="top:30px; position: absolute; left: 600px;absolute;z-index:5px;">

css

Their is nothing in special in css just we are setting the cursor to move
[draggable]{
    cursor: move;
}

JavaScript

The main thing is JavaScript in the file we are controlling the drag and drop events
var x = '';
var y = '';
var shirt = '';

function dragOver(e){
 e.preventDefault();
}

function dragStart(e){
 shirt = e.target;//select the shirt

 if(e.offsetX === undefined){//get the x & y of the image
  x = e.layerX;
  y = e.layerY;
 }else{
  x = e.offsetX;
  y = e.layerY;
 }

 shirt.style.zIndex = 10;//set the image above the all
 shirt.style.opacity = '0.4'; //set image opacity 40%

 //when drag end remove image opacity
 shirt.addEventListener('dragend', function(){
  shirt.style.opacity = '1';
 }, false);
}


function dropHandler(e){
 e.preventDefault();
 //postion the shirt
 shirt.style.left = e.pageX - x + 'px';
 shirt.style.top = e.pageY - y + 'px';
}

document.querySelector('body').addEventListener('dragstart', dragStart, false);//when drag start
document.querySelector('body').addEventListener('dragover', dragOver, false);//when drag end
document.querySelector('body').addEventListener('drop', dropHandler, false);//when the image is drop


Like Us on Facebook / Add Hunk As Friend