How to enable mobile zoom function in kineticjs?

by scotty_walker , in category: Javascript , 3 months ago

How to enable mobile zoom function in kineticjs?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 3 months ago

@scotty_walker 

To enable mobile zoom function in KineticJS, you can follow these steps:

  1. Add the KineticJS library to your project.
  2. Create a stage and add a layer to it.
  3. Add shapes or images to the layer.
  4. Enable the kineticJS built-in mobile events like "onTouchStart", "onTouchMove", "onTouchEnd" etc.
  5. Use the scale method to zoom in or out on the shapes or images based on the touch event data.


Here is an example code snippet to demonstrate how to enable mobile zoom function in KineticJS:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var stage = new Kinetic.Stage({
    container: 'container',
    width: window.innerWidth,
    height: window.innerHeight
});

var layer = new Kinetic.Layer();
stage.add(layer);

var image = new Kinetic.Image({
    x: 0,
    y: 0,
    image: 'path/to/your/image.jpg',
    width: 200,
    height: 200
});
layer.add(image);

var initialScale = 1;
var pinchCenter;

layer.on('touchstart', function(e) {
    if (e.touches.length >= 2) {
        var touch1 = e.touches[0];
        var touch2 = e.touches[1];

        pinchCenter = {
            x: (touch1.pageX + touch2.pageX) / 2,
            y: (touch1.pageY + touch2.pageY) / 2
        };
    }
});

layer.on('touchmove', function(e) {
    if (e.touches.length >= 2) {
        var touch1 = e.touches[0];
        var touch2 = e.touches[1];

        var currPinchCenter = {
            x: (touch1.pageX + touch2.pageX) / 2,
            y: (touch1.pageY + touch2.pageY) / 2
        };

        var scale = image.scaleX() * (Math.sqrt((touch1.pageX - touch2.pageX) * (touch1.pageX - touch2.pageX) + (touch1.pageY - touch2.pageY) * (touch1.pageY - touch2.pageY)) / Math.sqrt((currPinchCenter.x - pinchCenter.x) * (currPinchCenter.x - pinchCenter.x) + (currPinchCenter.y - pinchCenter.y) * (currPinchCenter.y - pinchCenter.y)));

        image.scaleX(scale);
        image.scaleY(scale);

        pinchCenter = currPinchCenter;
        layer.draw();
    }
});


This code snippet demonstrates how to use the touchstart and touchmove events to enable pinch zoom functionality on an image in KineticJS. It calculates the scale factor based on the distance between two touch points and adjusts the image's scale accordingly.