【问题标题】:How can I cut out a shape if it goes outside of a canvas with javascript?如果形状超出了使用 javascript 的画布,我该如何剪出形状?
【发布时间】:2018-04-03 12:13:13
【问题描述】:
我想创建一个圆圈,如果它超出另一个形状,我想剪掉它的一部分。
例如,如果圆形的一半在正方形之外,则剪掉外面的所有内容,但不要剪掉里面的所有内容。像这样的sn-p,除了正方形之外的部分是隐藏的。我宁愿避免遮盖它,因为它会出现在另一个画布之上,覆盖整个屏幕。
代码
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
ctx.rect(20,20,100,100);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.arc(70, 90, 60, 0, Math.PI * 2, false)
ctx.stroke();
ctx.restore();
<html>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
【问题讨论】:
标签:
javascript
html5-canvas
【解决方案1】:
你可以clip()圈子,像这样;
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
ctx.rect(20,20,100,100);
ctx.stroke();
ctx.closePath();
ctx.clip(); // clip circle
ctx.beginPath();
ctx.arc(70, 90, 60, 0, Math.PI * 2, false)
ctx.stroke();
ctx.restore();
<html>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
【解决方案2】:
这是我为裁剪正方形的外部而调整的尺寸
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
ctx.rect(20,20,100,100);
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.arc(70, 90, 60, 10, -4*Math.PI * .05 , false)
ctx.stroke();
ctx.restore();
<html>
<body>
<canvas id="canvas"></canvas>
</body>
</html>