3.2.6 HTML5 Canvas Curve Detection Tutorial

To detect curves with KineticJS, we can create a curved shape and then attach an event listener using the on() method.
1
curve.on(eventType, handler(eventObject));

HTML5 Canvas Curve Detection Example


Open in new window
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
<head>
    <script src="http://www.html5canvastutorials.com/libraries/kinetic-v3.8.0.js">
    </script>
    <script>
        function writeMessage(messageLayer, message){
            var context = messageLayer.getContext();
            messageLayer.clear();
            context.font = "18pt Calibri";
            context.fillStyle = "black";
            context.fillText(message, 10, 25);
        }
 
        window.onload = function(){
            var stage = new Kinetic.Stage("container", 578, 200);
            var curveLayer = new Kinetic.Layer();
            var messageLayer = new Kinetic.Layer();
 
            var curve = new Kinetic.Shape(function(){
                var canvas = this.getCanvas();
                var context = this.getContext();
 
                context.beginPath();
                context.moveTo(0, canvas.height * 0.7);
                context.bezierCurveTo(canvas.width * 0.2, -1 * canvas.height * 0.2, canvas.width * 0.7, canvas.height, canvas.width, canvas.height * 0.2);
 
                context.lineTo(canvas.width, canvas.height);
                context.lineTo(0, canvas.height);
                context.closePath();
                context.fillStyle = "blue";
                context.fill();
            });
 
            curve.on("mouseover", function(){
                writeMessage(messageLayer, "Curve detected!");
            });
 
            curve.on("mouseout", function(){
                writeMessage(messageLayer, "");
            });
 
            curveLayer.add(curve);
 
            stage.add(curveLayer);
            stage.add(messageLayer);
        };
    </script>
</head>
<body>
    <div id="container">
    </div>
</body>
Modified on February 24th, 2012 by Eric Rowell
comments powered by Disqus