summaryrefslogtreecommitdiff
path: root/public/js/brush.js
blob: 8d3eaf8041b3ba3c3a12762af103d9fa7f693d9f (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function Brush (b) {
  this.opt = b;
  var canvas = this.canvas = document.createElement("canvas");
  var ctx = this.ctx = canvas.getContext('2d');
  canvas.width = b.width;
  canvas.height = b.height || b.width;
  canvas.className = "brush";
  this.width = b.width;
  this.height = b.height || b.width;
  this.color = b.color;

  if (b.style == "soft") {
    var hw = Math.floor(b.width / 2);
    var r = clamp(b.width-1, 1, 1000);
    ctx.beginPath();
    var rad = ctx.createRadialGradient(hw, hw, 1, hw, hw, r);
    rad.addColorStop(0, b.color.alpha(b.color.a).toString());
    rad.addColorStop(0.5, b.color.alpha(0).toString());
    ctx.fillStyle = rad;
    ctx.arc(hw, hw, r, 0, Math.PI*2, false);
    ctx.fill();
  }
  else if (b.style == "hard") {
    var hw = Math.floor(b.width / 2);
    var r = clamp(b.width-1, 1, 1000);
    ctx.beginPath();
    var rad = ctx.createRadialGradient(hw, hw, 1, hw, hw, r);
    rad.addColorStop(0.5, b.color.toString() );
    rad.addColorStop(0.5, b.color.toString() );
    ctx.fillStyle = rad;
    ctx.arc(hw, hw, r, 0, Math.PI*2, false);
    ctx.fill();
  }
  else if (b.style == "pencil") {
    var hw = canvas.width / 2, hh = canvas.height / 2;
    var id = ctx.getImageData( 0, 0, canvas.width, canvas.height );
    var data = id.data;
    for (var i = -hw; i <= hw; i++) {
      for (var j = -hh; j <= hh; j++) {
        var xx = Math.floor( i + hw );
        var yy = Math.floor( j + hh );
        var mag = Trig.magnitude({ x: i, y: j });
        var offset = (yy * canvas.width + xx) * 4;
        data[ offset ]     = color.r;
        data[ offset + 1 ] = color.g;
        data[ offset + 2 ] = color.b;
        data[ offset + 3 ] = mag < r ? 1.0 : 0.0;
      }
    }
  }
}
Brush.prototype.copy = function(opt){
  return new Brush ( extend(opt, this.opt) )
}

function extend (h,a) {
  h = h || {};
  for (var i in a) {
    if (a.hasOwnProperty(i) && ! h.hasOwnProperty(i)) {
      h[i] = a[i];
    }
  }
  return h;
}

var brush;
function makeBrushes () {
  document.getElementById('brushes').innerHTML = '';
  fib(function(n){
    var b = new Brush({ style: 'pencil', color: color, width: n })
    b.canvas.onclick = function(){
      brush = b;
    }
    document.getElementById('brushes').appendChild( b.canvas );
    if (! brush) brush = b;
  });
}

makeBrushes();