【问题标题】:Make a hole in canvas background or in a rect在画布背景或矩形中打一个洞
【发布时间】:2013-12-22 14:18:41
【问题描述】:

我使用fabric.js,我需要一个透明矩形在画布上,但我需要使用背景。
问题是我需要背景在矩形下是透明的。

我创建了一个小提琴来说明我的问题: http://jsfiddle.net/goooseman/5xLE4/2/(我需要背景在正方形下透明)。

我认为在背景上打洞是不可能的,但我们可以使用另一个矩形作为背景。我创建了另一个小提琴来展示它:http://jsfiddle.net/goooseman/cNJwL/1/ 我使用此代码制作背景矩形:

var backgroundRect = new fabric.Rect({
    left: 0,
    top: 0,
    fill: 'red',
    width: canvas.width,
    height: canvas.height
});

但是我怎样才能在上面的矩形下面的背景矩形上打一个洞呢?

【问题讨论】:

标签: javascript html canvas fabricjs


【解决方案1】:

也许这会有所帮助(如在 this question 中找到的)。

您需要首先添加您想要做“洞”的画布背景对象。然后,创建一个新对象(刀具),并设置属性globalCompositeOperation = 'destination-out',然后将其添加到画布中。

就像这样:

var h = new fabric.Rect({width: canvas.width, height: canvas.height, fill: 'rgba(0,0,0,0.5)'})
var z = new fabric.Circle({radius: 100, top:100, left: 100, globalCompositeOperation: 'destination-out'})
canvas.add(h).add(z)

这样,您首先添加全局对象,然后将该对象添加为“切割器”。我认为它将充当所有东西的切割器,因此如果您“背后”有其他物体,它们也会被切割(尚未测试过)。

希望这会有所帮助!

【讨论】:

  • 完美的家伙。正是我需要的。我知道 canvas 的“destination-out”,但不确定如何在 fabricjs 中应用。
【解决方案2】:

如果只是一个正方形需要裁剪,你可以简单地在它周围画4个正方形,背景色。

fabric.StaticCanvas('canvas');
canvas.setHeight(300);
canvas.setWidth(300);

var bgrect = new fabric.Rect({
    left:0,
    top:0,
    fill: 'red',
    width: 100,
    height: 300,
});
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:200,
    top:0,
    fill: 'red',
    width: 100,
    height: 300,
});
canvas.add(bgrect);
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:100,
    top:0,
    fill: 'red',
    width: 100,
    height: 100,
});
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:100,
    top:200,
    fill: 'red',
    width: 100,
    height: 100,
});
canvas.add(bgrect);

this fiddle

【讨论】:

  • 谢谢你的回答,但是在我的项目中我使用的是圆角矩形,所以我不能这样做
【解决方案3】:

我知道我迟到了,但这对一些可以寻找答案的用户很有用

drawRectangleWithHole(document.getElementById('canvas').getContext('2d'), "black", 50, 50, 200, 200, 50, 50, 100, 100)

function drawRectangleWithHole(ctx, color, x, y, width, height, holeX, holeY, holeWidth, holeHeight) {
  ctx.fillStyle = color
  ctx.fillRect(x, y, holeX, height)
  ctx.fillRect(x, y, width, holeY)
  ctx.fillRect(x + holeX + holeWidth, y, width - (holeX + holeWidth), height)
  ctx.fillRect(x, y + holeY + holeHeight, width, height - (holeY + holeHeight))
}
<canvas id="canvas" width="300" height="300"><canvas>

注意孔的 X 和 Y 坐标是相对于矩形的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2020-12-15
    相关资源
    最近更新 更多