Multi-touch Scale Shape

获取Konva最新的信息

Note: This lab only works on devices that support multi-touch gestures such as iOS because it makes use of multiple touch events.

Instructions: Using a mobile device that supports multi-touch gestures such as iOS, drag and drop a shape by touching it and then dragging your finger across the screen, activate a shape by tapping on it, and scale an active shape by pinching the screen.

Konva Multi-touch Scale Shapeview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@4.0.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Multi-touch Scale Shape Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var lastDist = 0;
var startScale = 1;
var activeShape = null;

function getDistance(p1, p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height,
draggable: true,
x: width / 2,
y: height / 2,
offset: {
x: width / 2,
y: height / 2
}
});

var layer = new Konva.Layer();

var triangle = new Konva.RegularPolygon({
x: 190,
y: stage.height() / 2,
sides: 3,
radius: 80,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
draggable: true,
name: 'triangle'
});

var circle = new Konva.Circle({
x: 380,
y: stage.height() / 2,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
draggable: true,
name: 'circle'
});

stage.on('tap', function(evt) {
// set active shape
var shape = evt.target;
activeShape =
activeShape && activeShape.getName() === shape.getName()
? null
: shape;

// sync scene graph
triangle.setAttrs({
fill:
activeShape && activeShape.getName() === triangle.getName()
? '#78E7FF'
: 'green',
stroke:
activeShape && activeShape.getName() === triangle.getName()
? 'blue'
: 'black'
});

circle.setAttrs({
fill:
activeShape && activeShape.getName() === circle.getName()
? '#78E7FF'
: 'red',
stroke:
activeShape && activeShape.getName() === circle.getName()
? 'blue'
: 'black'
});

layer.draw();
});

stage.getContent().addEventListener(
'touchmove',
function(evt) {
var touch1 = evt.touches[0];
var touch2 = evt.touches[1];

if (touch1 && touch2 && activeShape) {
var dist = getDistance(
{
x: touch1.clientX,
y: touch1.clientY
},
{
x: touch2.clientX,
y: touch2.clientY
}
);

if (!lastDist) {
lastDist = dist;
}

var scale = (activeShape.scaleX() * dist) / lastDist;

activeShape.scaleX(scale);
activeShape.scaleY(scale);
layer.draw();
lastDist = dist;
}
},
false
);

stage.getContent().addEventListener(
'touchend',
function() {
lastDist = 0;
},
false
);

layer.add(triangle);
layer.add(circle);
stage.add(layer);
</script>
</body>
</html>
Next