Book Image

DART Essentials

Book Image

DART Essentials

Overview of this book

Table of Contents (16 chapters)
Dart Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Drawing into 2D canvas using onTouch events


Handling onTouch events is similar to drag and drop, so this is going to be very simple. Just one thing to note here: TouchEvent.touches is an instance of the TouchList class that contains all currently detected touches. In other words, you can handle multitouch devices as well. We're going to handle just the first touch found and draw lines as you move your finger over the screen. HTML is just a single canvas:

<canvas id="draw-canvas"></canvas>

Dart code listens to only two touch events:

import 'dart:html';

void main() {
  CanvasElement canvas = document.querySelector('#draw-canvas');
  CanvasRenderingContext2D context = canvas.getContext('2d');
  
  canvas.onTouchStart.listen((TouchEvent e) {
    // Move line start to the position where
    // the touch event began. We care only about the first touch.
    context.moveTo(e.touches[0].page.x, e.touches[0].page.y);
  });
    
  canvas.onTouchMove.listen((TouchEvent e) {
    context.lineWidth...