Coder Social home page Coder Social logo

manuelstofer / pinchzoom Goto Github PK

View Code? Open in Web Editor NEW
904.0 31.0 291.0 2.39 MB

A Javascript library providing multi-touch gestures for zooming and dragging on any DOM element.

Home Page: http://manuelstofer.github.com/pinchzoom/

License: MIT License

JavaScript 99.17% Shell 0.83%

pinchzoom's Introduction

PinchZoom.js

PinchZoom is a Javascript library providing multi-touch gestures for zooming and dragging on any DOM element.

Installation

Usage

Requirements

Initialisation

let el = document.querySelector('#my-id');
let pz = new PinchZoom(el, options);

Options


tapZoomFactor:      Zoom factor that a double tap zooms to. (default 2)
zoomOutFactor:      Resizes to original size when zoom factor is below this value. (default 1.3)
animationDuration:  Animation duration in milliseconds. (default 300)
maxZoom:            Maximum zoom factor. (default 4)
minZoom:            Minimum zoom factor. (default 0.5)
draggableUnzoomed:  Capture drag events even when the image isn't zoomed. (default true)
                    (using `false` allows other libs (e.g. swipe) to pick up drag events)
lockDragAxis:       Lock panning of the element to a single axis. (default false)
setOffsetsOnce:     Compute offsets (image position inside container) only once. (default false)
                    (using `true` maintains the offset on consecutive `load` and `resize`)
use2d:              Fall back to 2D transforms when idle. (default true)
                    (a truthy value will still use 3D transforms during animation)
useMouseWheel:      Use mouse wheel zoom and mouse drag. (default false)
useDoubleTap:       Use double tap zoom. (default true)
verticalPadding:    Vertical padding to apply around the image. (default 0)
horizontalPadding:  Horizontal padding to apply around the image. (default 0)

onZoomStart:        Callback for zoomstart event (params: Pinchzoom object, Event event) (default null)
onZoomEnd:          Callback for zoomend event (params: Pinchzoom object, Event event) (default null)
onZoomUpdate:       Callback for zoomupdate event (params: Pinchzoom object, Event event) (default null)
onDragStart:        Callback for dragstart event (params: Pinchzoom object, Event event) (default null)
onDragEnd:          Callback for dragend event (params: Pinchzoom object, Event event) (default null)
onDragUpdate:       Callback for dragupdate event (params: Pinchzoom object, Event event) (default null)
onDoubleTap:        Callback for doubletap event (params: Pinchzoom object, Event event) (default null)

Methods

let pz = new PinchZoom(myElement);

pz.enable(); // Enables all gesture capturing (is enabled by default)
pz.disable(); // Disables all gesture capturing
pz.destroy(); // Unmounts the zooming container and global event listeners

Example with callback

var myElement = document.getElementById("myElement");
var pz = new PinchZoom.default(myElement, {
    draggableUnzoomed: false,
    minZoom: 1,
    onZoomStart: function(object, event){
        // Do something on zoom start
        // You can use any Pinchzoom method by calling object.method()
    },
    onZoomEnd: function(object, event){
        // Do something on zoom end
    }
})

Events (deprecated)

Events are deprecated in favour of callbacks (see above).

Pinchzoom emits custom events you can listen to:


pz_zoomstart  Started to zoom
pz_zoomend    Stopped zooming
pz_zoomupdate Zoom factor updated
pz_dragstart  Started to drag the element
pz_dragend    Stopped to drag the element
pz_dragupdate Drag position updated
pz_doubletap  Resetting the zoom with double-tap

(if need be, the event names can be customized via options)

Release a New Version

  1. Make a bump commit (update package.json, package-lock.json and src)
  2. Create a new tag git tag -m "v2.2.0" v2.2.0
  3. Release new NPM version (npm whoami; npm publish)
  4. Push the code + the tag to Github (git push origin v2.2.0)
  5. Make a new Github release (https://github.com/manuelstofer/pinchzoom/releases)

Troubleshooting

  • If you have issues with invisible images, make sure that the image isn't absolutely positioned. In some cases that will cause trouble.

License

Licensed under the MIT License.

Github Page with demo

https://manuelstofer.github.io/pinchzoom/

pinchzoom's People

Contributors

aaronlayton avatar ahmed0saber avatar asin2501 avatar daichi-yamauchi avatar dbzx10299 avatar endel avatar english3000 avatar heisch avatar jcpmmx avatar levblanc avatar lorenzolotti avatar lrueegg avatar manuelstofer avatar micgro42 avatar nchen63 avatar neekey avatar oleksandr-danylchenko avatar patmead avatar sandstrom avatar simontuck avatar skumbagmeno avatar strygo avatar zer0 avatar zyniq82 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pinchzoom's Issues

Wrong docs example

This example can't work, please note the brackets 😆

let pz = new PinchZoom(el), options);

Can you give me some annotation for getCurrentZoomCenter function?I donnot understand.Thanks

getCurrentZoomCenter: function () {

  // uses following formula to calculate the zoom center x value
  // offset_left / offset_right = zoomcenter_x / (container_x - zoomcenter_x)
  var length = this.container.offsetWidth * this.zoomFactor,
    offsetLeft  = this.offset.x,
    offsetRight = length - offsetLeft - this.container.offsetWidth,
    widthOffsetRatio = offsetLeft / offsetRight,
    centerX = widthOffsetRatio * this.container.offsetWidth / (widthOffsetRatio + 1),

    // the same for the zoomcenter y
    height = this.container.offsetHeight * this.zoomFactor,
    offsetTop  = this.offset.y,
    offsetBottom = height - offsetTop - this.container.offsetHeight,
    heightOffsetRatio = offsetTop / offsetBottom,
    centerY = heightOffsetRatio * this.container.offsetHeight / (heightOffsetRatio + 1);

  // prevents division by zero
  if (offsetRight === 0) { centerX = this.container.offsetWidth; }
  if (offsetBottom === 0) { centerY = this.container.offsetHeight; }

  return {
    x: centerX,
    y: centerY
  };
},

On drag image zoom in

I have used this code and it works fine.
But I face issue when one image make zoom in then do slide or next to get next image and on that image when we drag it goes in zoom in.
Is there any suggestion?
Thanks :)

license

First of it all, we like your script.

But we have a problem with your License, it would force us to disclose the backend-code of our shop Application.

"As a web developer, it may not be possible to use a GPL licensed Javascript because disclosing the backend may pose security problems, not to mention that no one usually does this!

The solution, according to the GPL FAQ, is to add an exception:

As a special exception to the GPL, any HTML file which merely makes function calls to this code, and for that purpose includes it by reference shall be deemed a separate work for copyright law purposes. In addition, the copyright holders of this code give you permission to combine this code with free software libraries that are released under the GNU LGPL. You may copy and distribute such a system following the terms of the GNU GPL for this code and the LGPL for the libraries. If you modify this code, you may extend this exception to your version of the code, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version."

cited from moxiecode/plupload#1086
and http://www.gnu.org/licenses/gpl-faq.html#WMS
is it possible to add this exception to your Code?

Add ability to decouple pinch from element

I am working on an intricate canvas-based view of the cosmos. I need to call the API to set Right Ascension, declination, and field of view (in degrees between 60 and 0.00022910934437488727 of a degree). It would be great to be able to use this library to get rich js pinch event data, but not actually zoom as it will need to be converted into API calls. Does anyone have interest in collaborating with me to fork a version of this that abstracts the pinch events from the DOM element?

Hope so.
Ron

How to use zoomOutAnimation()

Hi, I love your plugin.
I currently need to use zoomOutAnimation() like mentioned in #16 but I can't seem to figure out how.
I tried using it on the jQuery element, but i get the 'is not a function' error:
$('.zoom-element').zoomOutAnimation()
Do I need to access the PinchZoom object? How would I do that after it was created?

Thanks in advance :)

Demo does not work

Such a nice plugin. But I can’t get it to work.
Loading down the pinch zoom-master and trying the demo various error occur.
First: the filename seems to be wrong:
In the html the line is: <script type="text/javascript" src="../src/pinchzoom.js"></script>
In the folder the name of the file actually is: pinch-zoom.js
Changing this line to: script type="text/javascript" src="../src/pinch-zoom.js"></script> then
new errors occur:
SyntaxError: Unexpected keyword 'export'
ReferenceError: Can't find variable: PinchZoom

Cannot slide up and down

When i use this plug that i can not slide up and down this page,
the version is v2.3.0
How can i solve this problem,some code as follow:
`
import PinchZoom from './utils/PinchZoom '

.......more dom

let pz = new PinchZoom(document.getElementById('outer-container'),{})

<style> .outer-container{ width:100%; height:100%; position:relative; } </style>

`

API change

The current API is:

new PinchZoom($('#your-element'), options);

As jQuery is necessary, the API should be jQuery like:

$('#your-element').pinchZoom(options);

Smooth pinching/dragging

If the target element isn't an image like demonstrated, the events won't be smooth. I've tested this with 10 KB lorem ipsum test content.

Can bind zoom to click, dbclick,...on PC

It seems work well on device, but I want to bind zoom function to click, dbclick,... in PC web. I tried to override pinchzoom.js but not successful. Does anyone give me some advice.
Thanks and regards!

Create multi TouchEvents programmatically to zoom

My device using TUIO, not mobile touch, so I have to create touch events programmatically to trigger pinch-zoom.umd.js
https://jsbin.com/baginicari/edit?js,console,output

I have tried
myElement = document.querySelector('#g2');
sendTouchEvent(247, 379, myElement, 'touchstart');
sendTouchEvent(317, 591, myElement, 'touchstart');

sendTouchEvent(257, 389, myElement, 'touchmove');
sendTouchEvent(307, 581, myElement, 'touchmove');

sendTouchEvent(267, 399, myElement, 'touchmove');
sendTouchEvent(297, 571, myElement, 'touchmove');

but the touchList never exceed 1. Pictures can move but can't zoom.
Can somebody help?

function sendTouchEvent(x, y, element, eventType) {
  const touchObj = new Touch({
   identifier: Date.now(),
   target: element,
   clientX: x,
   clientY: y,
   pageX: x,
   pageY: y,
   screenX: x,
   screenY: y,
   radiusX: 2.5,
   radiusY: 2.5,
   rotationAngle: 0,
   force: 0.5,
  });

  const touchEvent = new TouchEvent(eventType, {
    cancelable: true,
    bubbles: true,
    touches: [touchObj],
    targetTouches: [],
    changedTouches: [touchObj]
  
  });

  element.dispatchEvent(touchEvent);
}

Can't zoom to the bottom.

I'm using this plugin for zooming images. I have a HTML DIV element and inside there are multiple images, normally 3-4.

My problem: when i zoom-in the first image (at the top) and then try to scroll to the bottom of the last image. I can't scroll to the bottom when zoomed in (the scrolling stops on 1/4 of the last image). If i zoom-out then i can scroll to the bottom again.

This happens only when there are multiple HTML IMG element inside the HTML DIV element. If there is only one image then everything works fine.

Any idea why this is happening or how i could make this work? Or how to use this when you have multiple images on the same html page?

Add documentation for required markup & css

It would be good to have documentation on any html & css requirements.

For example, can it be attached to any html element?
Does the element it is attached to need any specific css, like positioning, height, width, etc?

If not it would be good to say there are no restrictions, just so people know.

How to tell if zoomed in or not?

I'm currently trying to add a class to the body when PinchZoom is zoomed in and remove it when it's back in original scale.
I managed to listen to the zoom start event, but zoom end doesn't seem to trigger when on original scale, I'm not sure when zoom end triggers.
Also with the double tap event I can't tell if I'm zooming in or out.
So, is there a way to get the current or targeted zoom factor (or any other way) so I can tell if the image is zoomed in or not?

Thanks a lot.

pinch-zoom-container getting height 0px

After I attach pinch zoom to my element (a div with an image and text inside) the pinch zoom container gets this markup:

<div class="pinch-zoom-container" style="overflow: hidden; position: relative; height: 0px;">

and I cannot see my image.

If I manually change the height to something like 700px then the image is visible.

Any ideas of what might be the problem?

Images and text appear blurred

Hello there!

Thanks once again for this fantastic plugin! My images and text appear blurred when I zoom in. Any ideas what could be happening?

Thanks,
Vasanth

License set to MIT?

what speaks against an MITStyle License like jquery et al?
right now you can't use this Script in an CMS without compromising your backoffice code.

In `src/pinch-zoom.js`, please change `const` keyword to `var` in function `getCurrentZoomCenter`

Would you please change the const keyword to var in src/pinch-zoom.js?

image

It triggers error in low version browsers:

Const declarations are not supported in strict mode

Function getCurrentZoomCenter is the only place that has the const keyword. In other functions of src/pinch-zoom.js, and the whole dist/pinch-zoom.umd.js, you are using var consistently.

Reason of the error:

In your package.json, module field is set to src/pinch-zoom.js.

so when we import your plugin-in like so:

import PinchZoom from 'pinch-zoom-js';

we are importing src/pinch-zoom.js, which has the const keyword.

If in our project's webpack setting, we exclude node_modules (which seems to be default settings of webpack) like so:

{
    test: /\.js$/,
    loader: 'babel-loader',
    exclude: /node_modules/
}

or so:

{
    test: /\.js$/,
    loader: 'babel-loader',
    include: [
        resolve('src')
    ]
}

webpack will not compile src/pinch-zoom.js in node_modules, and lead to the error.

Although including node_modules/pinch-zoom-js in webpack settings manually when coming across this problem is a workaround, modifying from the source will save the world in one shot. :)

Rotate and drag on single fingure

Hi

I want to have Rotate, drag by single finger and pinch zoom by tow fingers.
This plugin dose not support pinch zoom only, is it possible for you to support above mentioned things as well ?.

Error `undefined is not an object (evaluating 't.x')`, probably related to event.touches

The error message:
TypeError · undefined is not an object (evaluating 't.x') -- in 'getDistance'

screen shot 2018-09-28 at 12 00 52 pm

getDistance has an undefined argument.

            getDistance = function (a, b) {
                var x, y;
                x = a.x - b.x; // undefined.x => TypeError
                y = a.y - b.y;
                return Math.sqrt(x * x + y * y);
},

It is invoked by calculateDistance--which has as its first argument startTouches.

startTouches is initialized here:

var detectGestures = function (el, target) {
        var interaction = null,
            fingers = 0,
            lastTouchStart = null,
            startTouches = null,

Looking within the 'touchmove' event handler,

        el.addEventListener('touchmove', function (event) {
            if(target.enabled && !target.isDoubleTap) {
                if (firstMove) {
                    updateInteraction(event);
                    if (interaction) {
                        cancelEvent(event);
                    }
                    startTouches = targetTouches(event.touches);
                } else {
                    switch (interaction) {
                        case 'zoom':
                            target.handleZoom(event, calculateScale(startTouches, targetTouches(event.touches)));
break;

startTouches is mutated in the if block.

Given that the error occurs within getDistance and NOT calculateScale (in the else block):

calculateScale = function (startTouches, endTouches) {
                var startDistance = getDistance(startTouches[0], startTouches[1]),
                    endDistance = getDistance(endTouches[0], endTouches[1]);
                return endDistance / startDistance;
},

this means startTouches is being properly mutated from null to an array, and there must be a case where event.touches.length === 1 or 0, meaning startTouches[1] or endTouches[1] is undefined.

Combine pinchzoom with tilezoom

I read that pinchzoom can be combined with other libraries (swipe.js example). I tried to combine it with tilezoom (https://github.com/ematsakov/tilezoom). Because of my weak programming skills I was not able to realise the combination. Perhaps one of you is interested in combining the libraries to or is able to give a hint?

Thanks in advance

elEglon

Height for the container in the initialization of the script is not correct which hides the element

So, I was testing this library for the first time using the example given in the doc, but it didn't work. I was able to track the problem. I changed the following to the way it was in a previous release.

updateAspectRatio: function() {
  // current
 // this.setContainerY(this.container.parentElement.offsetHeight);
 // fix 
 this.setContainerY(this.getContainerX() / this.getAspectRatio());
},

This is what I used when the problem occurred:
My HTML.

<div class='parent'>
  <div class='image-container'>
      <img src='/images/Bowser.png'></div>
  </div>
</div>
let el = document.querySelector('.image-container');
let pz = new PinchZoom(el, {});

It didn't show anything until I made the change. I found out that when this library initializes, it sets the 'image-container' absolute and generates 'this.container' element with an relative position, the 'this.container' 's offsetHeight is zero which parent is also zero.

Unbind events functionality

Is there is way to unbind elements after they are initialised? To remove listeners / avoid memory leaks / etc when we remove the elements from the DOM to show new elements.

I'm attempting to use pinchzoom.js in a touch-gallery, and I will often remove collections of initialised images to add new ones. Are the events automatically removed when I remove the elements from the DOM or do we need an "unbind" functionality?

Listen to custom events

How can i listen to the custom events in pinchzoom plugin. Please provide me a sample code

Double Tap from mobile devices

Hi, I encounter an issue while I double tape in my touch screen to zoomIn or zoomOut. The precision is not accurate on touch screen. However it does work well once I double click from the "remote device" debugger.

Packaging

Update packaging. Add support for component.js, browserify, bower, npm.

Extend documentation

For example the following is missing:

  • An example with events
  • If the entire options are optional or if an empty object is required ({})
  • Passing parameters of event callbacks
  • Method example (e.g. instance.enable())
  • Explicitly named option types (boolean, number, ...)
  • ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.