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 = 2;
    context.strokeStyle = "#FF0000";
    // Move a line to where I moved my finger.
    context.lineTo(e.touches[0].page.x, e.touches[0].page.y);
    // Draw the line.
    context.stroke();
  });
  
  // Set canvas size to documents size. With this, touch
  // coordinates will be the same as canvas coordinates.
  void resize() {
    canvas.width = document.body.client.width;
    canvas.height = document.body.client.height;
  }
  resize();
  // Add event listener on windows resize in order to have
  // always the canvas size equal to the windows size.
  window.onResize.listen((Event e) => resize());
}

Note that we resized the canvas to the size of the document. If we performed some demanding drawings, we could use a simple trick by setting width and height canvas attributes to, for example, half the document dimensions. This would make the canvas draw only half the size (that's one-fourth of the pixels than the original size) and then scale the result to fit entire canvas. This would speed up rendering a lot, but the final image would probably be a little blurry. The same effect is possible with CSS3's scale statement.

Drawing into 2D canvas using onTouch events

We can use Developer Tools to emulate mobile touch events just like we did with device rotation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.126.56