HTML5 canvas javascript

HTML5 canvas javascript

我有透明模式的笔刷,我需要在顶部绘制时像这样变暗:

现在在顶部绘画时我得到了这样的相同颜色:

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>

无法在自身上使用 alpha 绘制多段线。 因此,为了让您的线图代码使用 alpha,我将您的折线图分成几段图。

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();
}

实际操作:jsfiddle

请注意,此代码性能不佳。要获得高效的代码,需要进行批处理。