具有一致的Alpha值的HTML5画布笔触

时间:2018-11-28 16:18:28

标签: javascript html5 canvas alpha overlapping

我正在开发一种图像遮罩工具,可以帮助用户在基础图像上标记某些区域。我希望蒙版具有一致的alpha值。屏蔽工具将在HTML5 canvas中实现。

我面临的问题是,当我创建多个重叠的笔触时,它们的alpha值会堆叠,从而使其在重叠中的透明度降低。不管笔触重叠如何,我都希望有一个一致的alpha值,因为用户可能需要多次笔触才能完全遮盖一个区域。

Here is the attached fiddle:

http://jsfiddle.net/o5x70fbd/

让我知道这是否是已知的解决方案

1 个答案:

答案 0 :(得分:1)

我不知道这是否是您正在寻找的解决方案。我的想法是使用2个画布。在第一个画布中,笔触的颜色是不透明的。该画布是隐藏的。我正在使用"/a/path/to/foo.tar",但您可以让它独立于DOM。

然后使用display:none将第一个画布复制为第二个图像。这将为您提供一致的alpha值。

我对您的代码所做的更改:我将点放置在数组中,并使用这些点进行绘制:

ctx2.globalAlpha = .5;
var canvas = document.getElementById("myCanvas");
var canvas2 = document.getElementById("_2");
var ctx = canvas.getContext("2d");
var ctx2 = _2.getContext("2d");
var drawing = false;
let points = [];

var painting = document.getElementById("paint");
var paint_style = getComputedStyle(painting);
canvas.width = canvas2.width = parseInt(paint_style.getPropertyValue("width"));
canvas.height = canvas2.height = parseInt(
  paint_style.getPropertyValue("height")
);

var mouse = {
  x: 0,
  y: 0
};

let count = -1;
ctx.lineWidth = 30;
ctx.lineJoin = "round";
ctx.lineCap = "round";

_2.addEventListener(
  "mousemove",
  function(e) {
    if (drawing) {
      mouse.x = e.pageX - this.offsetLeft;
      mouse.y = e.pageY - this.offsetTop;
      points[count].push({ x: mouse.x, y: mouse.y });
      onPaint();
    }
  },
  false
);

_2.addEventListener(
  "mousedown",
  function(e) {
    drawing = true;
    count++;
    mouse.x = e.pageX - this.offsetLeft;
    mouse.y = e.pageY - this.offsetTop;
    let ry = [];
    ry.push({ x: mouse.x, y: mouse.y });
    points.push(ry);
  },
  false
);

_2.addEventListener(
  "mouseup",
  function() {
    drawing = false;
    onPaint();
  },
  false
);

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

  points.forEach(ry => {
    ctx.beginPath();
    ctx.moveTo(ry[0].x, ry[0].y);
    ry.forEach(p => {
      ctx.lineTo(p.x, p.y);
    });
    ctx.strokeStyle = "#00CC99";
    ctx.stroke();
  });

  ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  ctx2.globalAlpha = 0.5;
  ctx2.drawImage(canvas, 0, 0);
}
body {
    margin: 0px;
    padding: 0px;
}

#paint {
    width: 98%;
    height: 550px;
    border: 5px solid red;
}

#myCanvas{display:none;}

#_2{background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/castell.jpg)}