画布-填充用多条路径创建的形状

Canvas - Fill a shape created with multiple paths

本文关键字:创建 路径 填充 画布      更新时间:2023-09-26

我想做什么

我想画一个自定义形状(例如一个简单的矩形),每个边缘有不同的颜色。我可以用四条路径,效果很好。但是,这样做,我似乎无法填充形状。

尝试另一种方式,我可以用一条路径绘制形状并填充它,但是在这种情况下,我不能为边缘使用不同的颜色,因为最后的fillStyle会覆盖之前的,即使我单独描边。

是否有可能混合两者,通过单独着色子路径,或通过填充由多条路径组成的形状?

在画布上使用不同的"图层",一个用于填充颜色形状,另一个用于您拥有的每个颜色路径,z-index在画布上不工作,只需确保您先绘制下面的内容,并将所有内容包装在组<g>标签上,以便更容易操作

经过一些实验,我设法解决了我的问题。这不是一个理想的解决方案,因为它有一些开销,但它工作得很好。

在绘制操作的开始,我将目标坐标存储在一个数组中,并一次又一次地绘制整个内容。每次运行都是一条新的路径。使用.globalCompositeOperation = "destination-over",我可以在下绘制线,这样每条线都可以有不同的颜色。

在绘制操作结束时,数组包含了形状的所有坐标,因此.fill()方法可以填充路径。

我希望它能帮助别人:

// get the canvas context
var ctx = document.getElementById("myCanvas").getContext("2d");
// init shape array
var shape = [];
shape.push({
  x: 0,
  y: 0
}); // or any other starting point
// let's try
draw(20, 20);
draw(40, 40);
draw(60, 60);
// this is how we draw
function draw(x, y) {
  // this is important
  // see: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  ctx.globalCompositeOperation = "destination-over";
  // this is just to be more visible
  ctx.lineWidth = 10;
  // get a random color
  ctx.strokeStyle = myRandomColor();
  // save target coordinates
  shape.push({
    x: x,
    y: y
  });
  // reset the path
  ctx.beginPath();
  // jump to the start point
  ctx.moveTo(shape[0].x, shape[0].y);
  // draw the whole stuff
  for (var i = 0; i < shape.length; i++) {
    ctx.lineTo(shape[i].x, shape[i].y);
  }
  ctx.stroke();
}
function myRandomColor() {
  var colors = ["red", "green", "blue", "yellow", "pink"];
  var rand = Math.round(Math.random() * 5);
  return colors[rand];
}
<canvas id="myCanvas"></canvas>