HTML5 Canvas 移动触摸事件教程

要在移动设备上使用 Konva 绑定事件处理程序到形状,我们可以使用 on() 方法。
on() 方法需要一个事件类型和一个在事件发生时执行的函数。
Konva 支持 touchstarttouchmovetouchendtapdbltapdragstartdragmovedragend 移动事件。

对于更复杂的手势,如 rotate,请查看 手势演示

如果您需要整个舞台的平移和缩放逻辑,请查看 多点触控缩放舞台演示

注意:此示例仅适用于移动设备,因为它使用触摸事件而不是鼠标事件。

说明:在三角形上滑动您的手指查看触摸坐标,并在圆圈上进行触摸开始和触摸结束。

Konva Mobile_Events Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/konva@9.3.18/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Mobile Touch Events Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>

<body>
<div id="container"></div>
<script>
function writeMessage(message) {
text.text(message);
}

var stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

var layer = new Konva.Layer();

var triangle = new Konva.RegularPolygon({
x: 80,
y: 120,
sides: 3,
radius: 80,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4,
});

var text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black',
});

var circle = new Konva.Circle({
x: 230,
y: 100,
radius: 60,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});

triangle.on('touchmove', function () {
var touchPos = stage.getPointerPosition();
var x = touchPos.x - 190;
var y = touchPos.y - 40;
writeMessage('x: ' + x + ', y: ' + y);
});

circle.on('touchstart', function () {
writeMessage('Touchstart circle');
});
circle.on('touchend', function () {
writeMessage('Touchend circle');
});

layer.add(triangle);
layer.add(circle);
layer.add(text);

// add the layer to the stage
stage.add(layer);
</script>
</body>
</html>