Javascript 我可以在两个形状的上面画一个组合的笔划/轮廓吗?

Javascript 我可以在两个形状的上面画一个组合的笔划/轮廓吗?,javascript,html,canvas,Javascript,Html,Canvas,到目前为止,我有: 但是很明显,笔划是不正确的,它应该在不规则形状的周围,而不是交叉 有没有可能通过一些全球合成、操作、体操或其他方式来实现这一点,或者我必须“一步一步”地画它,而不是在它们上面画一个圆圈和一个矩形 $(document).ready(function() { var d_canvas = document.getElementById('canvas'); var context = d_canvas.getContext('2d'); context.beginPath();

到目前为止,我有:

但是很明显,笔划是不正确的,它应该在不规则形状的周围,而不是交叉

有没有可能通过一些全球合成、操作、体操或其他方式来实现这一点,或者我必须“一步一步”地画它,而不是在它们上面画一个圆圈和一个矩形

$(document).ready(function() {
var d_canvas = document.getElementById('canvas');
var context = d_canvas.getContext('2d');
context.beginPath();

var circle_x = 150;
var circle_y = 150;
var radius = 50;
var corners = 10;
var width = (radius*2)/1.1
var height = 50;
var x = circle_x - width/2;
var y = circle_y - 70;

context.moveTo(x + corners, y);
context.lineTo(x + width - corners, y);
context.quadraticCurveTo(x + width, y, x + width, y + corners);
context.lineTo(x + width, y + height - corners);
context.quadraticCurveTo(x + width, y + height, x + width - corners, y + height);
context.lineTo(x + corners, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - corners);
context.lineTo(x, y + corners);
context.quadraticCurveTo(x, y, x + corners, y);

context.arc(circle_x, circle_y, radius, 0, 2*Math.PI);

context.fillStyle = "#000000";
context.fill();
context.strokeStyle = "red";
context.stroke();
context.endPath();
});

您可以通过剪裁实现所需的效果:
-填充和笔划圆形矩形
-填充下圆
-然后,在圆的右侧划一划:
--首先剪辑整个画布
--然后将上直肌夹出
--现在划圆圈

使用线宽0执行此操作,因为您希望精确定义rect

现在你可以画画了,它会画除矩形外的所有地方

我将上矩形近似为正则矩形,在本例中这是正确的:


您可以使用合成来勾勒组合形状的轮廓

演示:

如果要同时绘制和填充矩形+圆弧,只需在绘制()之后进行填充()

如果只需要轮廓笔划,可以使用合成:

drawYourPath();
ctx.stroke();
ctx.globalCompositeOperation="destination-out";
ctx.fill();
此代码可以稍微增强

  • 保存/恢复上下文,这样我们就不会无意中打开合成
  • 加倍线宽,因为合成将删除一半笔划宽度
修订守则:

ctx.save();
drawYourPath();
ctx.lineWidth*=2;
ctx.stroke();
ctx.globalCompositeOperation="destination-out";
ctx.fill();
ctx.restore();
可能重复的
drawYourPath();
ctx.stroke();
ctx.globalCompositeOperation="destination-out";
ctx.fill();
ctx.save();
drawYourPath();
ctx.lineWidth*=2;
ctx.stroke();
ctx.globalCompositeOperation="destination-out";
ctx.fill();
ctx.restore();