Area and saturation of a circle using horizontal and vertical pan events

Basic touch gestures with Hammer

by Génesis García Morilla

HTML

<script src="https://hammerjs.github.io/dist/hammer.js"></script>
<p>Area <span id="area">0</span>%  Saturation <span id="saturation">0</span>%</p>
<div id="container" class="inside-center">
  <div id="circle"></div>
</div>
<p>Pan horizontally and vertically to see what happens</p>
<p>Pinch if you have multi-touch</p>

CSS

p {
  text-align: center;
  color: #2b2b2b;
  font-family: "Roboto Condensed";
  text-transform: uppercase;
}

/* Horizontal and vertical alignment for elements inside */
.inside-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

#container {
  width: 300px;
  height: 300px;
  margin: auto;
  background-color: #181818;
}

#circle {
  width: 0;
  height: 0;
  background-color: hsl(40, 100%, 60%);
  border-radius: 50%;
  transition: all 0.2s ease-out;
}

JavaScript

var area = 0, saturation = 0;
var $area = document.querySelector("#area");
var $saturation = document.querySelector("#saturation");
var $circle = document.querySelector("#circle");
var scale;

// Our events are going to be in the body
var mc = new Hammer(document.querySelector("body"));
var direction;

// Our specific pan event
mc.add( new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 30 }) );
// Pinch is not active by default
mc.add(new Hammer.Pinch());

// Listen to events
mc.on("panleft panright pandown panup press", function(e) {
	direction = e.type;
});
    
mc.on("panend", function(e) {
	if ((direction === "panleft") && area > 0)
		area -= 10;
  if ((direction === "panright") && area < 100)
  	area += 10;
  if ((direction === "pandown") && saturation > 0)
		saturation -= 10;
  if ((direction === "panup") && saturation < 100)
  	saturation += 10;

  $area.textContent = area;
  $saturation.textContent = saturation;
  $circle.style.backgroundColor = "hsl(40, " + saturation + "%, 60%)";
  $circle.style.width = area + "%";  
  $circle.style.height = area + "%";
});

// only with multi-touch
mc.on("pinchstart", function(e) {
  scale = e.scale;
});

mc.on("pinchmove", function(e) {
  if (Math.abs(e.scale - scale) < 0.10) return; // minimum

  if ((e.scale < scale) && area > 0) area -= 10;
  if ((e.scale >= scale) && area < 100) area += 10;
  scale = e.scale;

  $area.textContent = area;
  $circle.style.width = area + "%";
  $circle.style.height = area + "%";
});