HTML5 Canvas 桌面和移动设备事件支持教程


注意:这个演示可能已经过时,因为现代浏览器支持指针事件。你也可以在 Konva 中使用指针事件。查看 指针事件演示。但如果你不想使用指针事件,请继续阅读…

为了为使用 Konva 的桌面和移动应用程序的形状添加事件处理程序,我们可以使用 on() 方法并传入成对的事件。
例如,为了在桌面和移动应用程序上触发 mousedown 事件,我们可以使用 "mousedown touchstart" 事件对来覆盖这两种媒介。
为了在桌面和移动应用程序上触发 mouseup 事件,我们可以使用 "mouseup touchend" 事件对。
我们还可以使用 "dblclick dbltap" 事件对来绑定适用于桌面和移动设备的双击事件。

说明:在桌面或移动设备上,对圆形进行 mousedown、mouseup、touchstart 或 touchend 操作,以观察相同的功能。

Konva Desktop_and_Mobile 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 Desktop and Mobile Events Support 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 text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 20,
text: '',
fill: 'black',
});

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

/*
* mousedown and touchstart are desktop and
* mobile equivalents so they are often times
* used together
*/
circle.on('mousedown touchstart', function () {
writeMessage('Mousedown or touchstart');
});
/*
* mouseup and touchend are desktop and
* mobile equivalents so they are often times
* used together
*/
circle.on('mouseup touchend', function () {
writeMessage('Mouseup or touchend');
});

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

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