Freehand Polygons

Just a canvas that allow you to draw a polygon with the mouse and stores the points.

by TigerAsks

HTML

<!DOCTYPE html>
<html>

  <head>
    <title>HTML5 input </title>
  </head>

  <body onload="init()">

    <input type="button" value="Clear" onclick="clearCanvas()"><br>
    <canvas id="mycanvas" width="500" height="500">
      Canvas element not supported.
    </canvas>
  </body>

</html>

CSS

#mycanvas {
  border: solid red;
}

JavaScript

var canvas;
var ctx;
var lastPt = null;
var clicked = false;

var points = [];

function init() {
  var touchzone = document.getElementById('mycanvas');
  touchzone.addEventListener('touchmove', drawTouch, false);
  touchzone.addEventListener('touchend', endTouch, false);
  touchzone.addEventListener('mousedown', startDrawClick, false);
  touchzone.addEventListener('mousemove', drawClick, false);
  touchzone.addEventListener('mouseup', endClick, false);
  ctx = touchzone.getContext('2d');
  canvas = touchzone;
}

function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function drawTouch(e) {
  e.preventDefault();
  draw(e.touches[0].pageX, e.touches[0].pageY);
}

function endTouch(e) {
  e.preventDefault();
  end();
}

function startDrawClick(e) {
  e.preventDefault();
  clicked = true;
  drawClick(e);
}

function drawClick(e) {
  e.preventDefault();
  if (!clicked) return;
  draw(e.offsetX, e.offsetY);
}

function endClick(e) {
  e.preventDefault();
  end();
}

function draw(x, y) {
  if (!!lastPt) {
    ctx.beginPath();
    ctx.moveTo(lastPt.x, lastPt.y);
    ctx.lineTo(x, y);
    ctx.stroke();
  }
  lastPt = {
    x: x,
    y: y
  };
}

function end() {
  lastPt = null;
  clicked = false;
}