360 Draggable Sprite
by Elijah Tate
HTML
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/latest/utils/Draggable.min.js"></script>
<h1>360 Draggable Sprite</h1>
<div class='threeSixtySlider' id='threeSixtySlider'>
<div id='spriteContainer'></div>
</div>
<p>Drag the box left/right to control the sprite's position.</p>
CSS
body {
text-align: center;
font: normal 14px sans-serif;
background: #000000;
color: white;
}
.threeSixtySlider {
margin: 20px auto;
padding: 60px;
width: 128px;
background: #FCFEFC;
border-radius: 5px;
}
#spriteContainer {
width: 128px;
height: 128px;
background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/29123/heart.png);
/* horizontal spritesheet - image from http://preloaders.net */
background-repeat: repeat-x;
}
JavaScript
/**Note: Another way of creating this would be to return an anonamous object with the Module pattern that contains all of this functionality. In that way we could control our namespace */
var threeSixtyRotation = (function (spritePXSize, numberOfSpriteImages) {
// create a dummy element that will register the drag events. We could in the future tie this in with
// a visual slider if needed
var threeSixtySlider = document.createElement('div');
//add our dummy element to the DOM for the lastest Draggable
document.body.appendChild(threeSixtySlider);
// we attach all of the vars to the element for cleanliness:
// element to init dragging
threeSixtySlider.slider = document.getElementById('threeSixtySlider');
// element with the sprite sheet
threeSixtySlider.sprite = document.getElementById('spriteContainer');
// pixel size of our individual sprite images
threeSixtySlider.spritesize = spritePXSize;
// let's keep our multiplier in a reasonable range
threeSixtySlider.spritecount = numberOfSpriteImages;
// how many pixels the user must drag before we update to new sprite image
threeSixtySlider.pixelsperincrement = 25;
// sprite changer values
threeSixtySlider.multiplier = threeSixtySlider.lastmultiplier = 0;
// create the 360 degree slider
Draggable.create(threeSixtySlider, {
type: 'x',
trigger: threeSixtySlider.slider,
// reset the targets position after drag ends, so onDrag doesn't need to deal with an offset
bounds: {
minX: 0,
maxX: 0,
minY: 0,
maxY: 0
},
// stop a slow down effect when dragging away
edgeResistance: 0,
cursor: 'e-resize',
onDrag: function () {
// there is an extra drag event fired on mouse up that has x = 0, so check this.isDragging to skip that last one
if (this.isDragging) {
var t = this.target; // the dummy...