首页 > 解决方案 > 在 JavaScript 画布 API 中设置允许的绘图区域

问题描述

我正在使用 JavaScript 画布 API 进行免费绘图。我坚持掩盖允许绘制的区域 - 在我的示例中,它应该只是语音气泡区域。我正在使用这个 Vue 组件:https ://github.com/sametaylak/vue-draw/blob/master/src/components/CanvasDraw.vue

draw(event) {
  this.drawCursor(event);
  if (!this.isDrawing) return;
  if (this.tools[this.selectedToolIdx].name === 'Eraser') {
    this.canvasContext.globalCompositeOperation = 'destination-out';
  } else {
    this.canvasContext.globalCompositeOperation = 'source-over';
    this.canvasContext.strokeStyle = this.tools[this.selectedToolIdx].color;
  }
  this.canvasContext.beginPath();
  this.canvasContext.moveTo(this.lastX, this.lastY);
  this.canvasContext.lineTo(event.offsetX, event.offsetY);
  this.canvasContext.stroke();
  [this.lastX, this.lastY] = [event.offsetX, event.offsetY];
},
drawCursor(event) {
  this.cursorContext.beginPath();
  this.cursorContext.ellipse(
    event.offsetX, event.offsetY,
    this.brushSize, this.brushSize,
    Math.PI / 4, 0, 2 * Math.PI
  );
  this.cursorContext.stroke();
  setTimeout(() => {
    this.cursorContext.clearRect(0, 0, this.width, this.height);
  }, 100);
},

标签: javascriptvue.jscanvas

解决方案


有一个内置clip()方法将路径设置为剪切区域。

var ctx=document.getElementById("cnv").getContext("2d");
ctx.lineWidth=2;

ctx.strokeStyle="red";
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.stroke();                // 1.

ctx.strokeStyle="black";
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(100,10);
ctx.lineTo(100,60);
ctx.lineTo(30,60);
ctx.lineTo(10,80);
ctx.closePath();
ctx.stroke();                // 2.
ctx.clip();                  // 3.

ctx.strokeStyle="green";
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(100,0);
ctx.stroke();                // 4.
<canvas id="cnv"></canvas>

  1. 红线在 0,0 和 100,100 之间绘制,没有剪裁
  2. 气泡以黑色绘制
  3. 气泡设置为剪切区域
  4. 绿线在 0,100 和 100,0 之间绘制,并正确地夹在气泡中。

在实践中,您可能希望在气泡内有一个像素的剪切区域,因此是一个单独的路径(不是stroke()-d,只是clip()-ped),因此绘图不能修改气泡本身。如果现在按原样放大,您会看到绿线实际上过度绘制了气泡的内部像素(线宽为 2 个像素,而外部是“未损坏”的)。


推荐阅读