Drawing Canvas

Based on: http://stackoverflow.com/a/8398189/5857393

by MegaScience

HTML

<canvas id="theCanvas" width="400" height="400"></canvas>
<img id="canvasImg" class="blank" alt="Image Version"/>
<div class="colorSelector">
  <div>Choose Color</div>
  <div id="palette">
    <div data-color="green"></div>
    <div data-color="blue"></div>
    <div data-color="red"></div>
    <div data-color="yellow"></div>
    <div data-color="orange"></div>
    <div data-color="black"></div>
  </div>
  <div id="eraser">
    <div>Eraser</div>
    <div data-color="white"></div>
  </div>
</div>
<input type="button" value="Save" id="saveButton" />
<input type="button" value="Clear" id="eraseButton" />

CSS

canvas,
img {
  border: 2px solid black;
  background-color: white;
  display: inline-block;
}

img {
  border-color: red;
}

img.blank {
  display: none;
}

#palette div,
#eraser div[data-color] {
  width: 10px;
  height: 10px;
  border: 1px dotted black;
  display: inline-block;
}

JavaScript

// http://stackoverflow.com/questions/2368784/draw-on-html5-canvas-using-a-mouse

var canvasMech = {
  elems: {
    canvas: document.getElementById("theCanvas"),
    canvasImg: document.getElementById("canvasImg"),
    saveB: document.getElementById("saveButton"),
    eraseB: document.getElementById("eraseButton")
  },
  attrs: {
    flag: false,
    locats: [0, 0, 0, 0],
    curColor: "black",
    lineWidth: 2
  },
  init: function() {
    this.elems.ctx = this.elems.canvas.getContext("2d");

    //var colors = document.getElementById("palette").getElementsByTagName("div");
    var colors = document.querySelectorAll('div[data-color]');
    for (var i = 0, len = colors.length; i < len; i++) {
      colors[i].style.backgroundColor = colors[i].dataset.color;
      colors[i].addEventListener("click", this.setColor);
    }

    this.elems.canvas.addEventListener("mousemove", this.findxy.bind(this), false);
    this.elems.canvas.addEventListener("mousedown", this.findxy.bind(this), false);
    this.elems.canvas.addEventListener("mouseup", this.findxy.bind(this), false);
    this.elems.canvas.addEventListener("mouseout", this.findxy.bind(this), false);

    this.elems.saveB.addEventListener("click", this.saveToImg.bind(this), false);
    this.elems.eraseB.addEventListener("click", this.eraseCan.bind(this), false);
    this.elems.canvasImg.addEventListener("load", function() {
      this.classList.remove("blank");
    }, false);
  },
  setColor: function() {
    canvasMech.attrs.curColor = this.dataset.color;
    if (canvasMech.attrs.curColor === "white") canvasMech.attrs.lineWidth = 14;
    else canvasMech.attrs.lineWidth = 2;
  },
  drawLine: function() {
    this.elems.ctx.beginPath();
    this.elems.ctx.moveTo(this.attrs.locats[0], this.attrs.locats[1]);
    this.elems.ctx.lineTo(this.attrs.locats[2], this.attrs.locats[3]);
    this.elems.ctx.strokeStyle = this.attrs.curColor;
    this.elems.ctx.lineWidth = this.attrs.lineWidth;
    this.elems.ctx.stroke();
   ...