Search code examples
javascripthtmlcanvashtml5-canvasbrush

HTML5 canvas javascript


i have brush with transparency mode i need while drawing on the top get darker like this: enter image description here

Now while painting on the top i get same color like this:

var el = document.getElementById('c');
var ctx = el.getContext('2d');

ctx.lineWidth = 10;
ctx.lineJoin = ctx.lineCap = 'round';
ctx.globalAlpha = "0.2";
ctx.strokeStyle = "red";

var isDrawing, points = [ ];

el.onmousedown = function(e) {
  isDrawing = true;
  points.push({ x: e.clientX, y: e.clientY });
};

el.onmousemove = function(e) {
  if (!isDrawing) return;

  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  points.push({ x: e.clientX, y: e.clientY });

  ctx.beginPath();
  ctx.moveTo(points[0].x, points[0].y);
  for (var i = 1; i < points.length; i++) {
    ctx.lineTo(points[i].x, points[i].y);
  }
  ctx.stroke();
};

el.onmouseup = function() {
  isDrawing = false;
  points.length = 0;
};
canvas { border: 1px solid #ccc }
<canvas id="c" width="500" height="300"></canvas>


Solution

  • A polyline cannot be drawn with alpha on itself. So to make your line drawing code working with alpha, I separated your poyline drawing into several segment drawings.

    for (var i = 1; i < points.length; i++) 
    {
        ctx.beginPath();
        ctx.moveTo(points[i-1].x, points[i-1].y);
        ctx.lineTo(points[i].x, points[i].y);
        ctx.stroke();
    }
    

    see in action : jsfiddle

    Beware, this code is not performant. To have an efficient code, batching is needed.