JavaScript Library For 3D Touch Handling – Pressure

Category: Javascript , Recommended | September 29, 2020
Author: yamartino
Views Total: 32 views
Official Page: Go to website
Last Update: September 29, 2020
License: MIT

Preview:

JavaScript Library For 3D Touch Handling – Pressure

Description:

Pressure is a pure JavaScript library which provides a simple way to detect and handle 3D touch (or Force Touch introduced in New Mac and iPhone 6S) events on your webpage.

How to use it:

To get started, include the pressure.js JavaScript file in the document.

<script src="pressure.js"></script>

Get back a change value on all elements matching the selector.

Pressure.change('#el1', function(force, event){
  console.log(force);
  // "this" is the element(s) returned by the closure
  this.style.width = (200 * force + 200) + 'px';
  this.innerHTML = force;
});

Get back a change value on ONLY elements that support Force Touch (New Mac’s).

Pressure.changeForceTouch('#el2', function(force, event){
  this.style.width = Math.max((200 * force), 200) + 'px';
  this.innerHTML = force;
});

Get back a change value on ONLY elements that support 3D Touch (iPhone 6s & iPhone 6s Plus).

Pressure.change('#el3', function(force, event){
  this.style.width = (200 * force + 200) + 'px';
  this.innerHTML = force;
});

Example of change method with a failure closure. This structure can be used in any methods of Pressure. The failure block will return with an “error” and message showing why the device doesn’t support 3D Touch and Force Touch.

var block = {
  start: function(){
  },

  change: function(force, event){
    this.style.width = ((200 * force) + 200) + 'px';
    this.innerHTML = force;
    this.style.backgroundColor = "rgb(" + parseInt(map(force, 0, 1, 255, 0)) + ",0," + parseInt(map(force, 0, 1, 0, 255)) +")";
    this.style.color = force > 0.4 ? 'white' : 'black';
  },

  startDeepPress: function(event){
    // this is called on "force click" / "deep press", aka once the force is greater than 0.5
  },
  endDeepPress: function(){
    // this is called when the "force click" / "deep press" end
  },

  end: function(){
    this.style.width = '200px';
    this.innerHTML = 0;
    this.style.backgroundColor = 'red';
    this.style.color = 'black';
  },

  unsupported: function(){
    console.log(this);
    this.innerHTML = 'Your device / browser does not support this :(';
  }
}

Pressure.set('#el1', block);
Pressure.setForceTouch('#el2', block);
Pressure.set3DTouch('#el3', block);

function map(x, in_min, in_max, out_min, out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Changelog:

v2.2.0 (09/29/2020)

  • Fix for MacOS Safari

08/05/2018

  • v2.1.2

You Might Be Interested In:


Leave a Reply