HTML5 Canvas Custom Hit Detection Function Tutorial

To create a custom hit draw function for a shape with Konva, we can set
the drawHitFunc property. A hit draw function is the function that Konva
will use to draw a region used for hit detection. Using a custom draw hit
function can have several benefits, such as making the hit region larger
so that it’s easier for users to interact with a shape, making some portions
of a shape detectable and others not, or simplifying the hit draw function
in order to improve rendering performance.

Instructions: Mouseover, mouseout, mousedown, and mouseup over the star and
observe that the hit region is an over sized circle encompassing the shape.

Konva Custom_Hit_Region Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.rawgit.com/konvajs/konva/1.6.3/konva.min.js"></script>
<meta charset="utf-8">
<title>Konva Custom Hit Function 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.setText(message);
layer.draw();
}
var stage = new Konva.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Konva.Layer();
var text = new Konva.Text({
x: 10,
y: 10,
fontFamily: 'Calibri',
fontSize: 24,
text: '',
fill: 'black'
});
var star = new Konva.Star({
x: stage.getWidth() / 2,
y: stage.getHeight() / 2,
numPoints: 7,
innerRadius: 50,
outerRadius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
hitFunc: function(context) {
context.beginPath();
context.arc(0, 0, this.getOuterRadius() + 10, 0, Math.PI * 2, true);
context.closePath();
context.fillStrokeShape(this);
}
});
star.on('mouseover', function() {
writeMessage('Mouseover star');
});
star.on('mouseout', function() {
writeMessage('Mouseout star');
});
star.on('mousedown', function() {
writeMessage('Mousedown star');
});
star.on('mouseup', function() {
writeMessage('Mouseup star');
});
layer.add(star);
layer.add(text);
// add the layer to the stage
stage.add(layer);
</script>
</body>
</html>