重叠裁剪问题

Overlapping clipping issue

我在抓取用户 displayAvatar() 然后使用圆弧使图像变圆时遇到问题。这工作正常,但是,我需要在该图像的顶部放置一个圆圈,但由于之前的 clip()

,它被切成两半

没有 clip() : https://i.gyazo.com/b474c656f33a1f004f5e3becffcef527.png

clip() : https://i.gyazo.com/da13377cd3f6dc7516c2b8fd1f0f8ac9.png

我知道在 'With clip()' 图像中,弧形边框似乎显示在剪辑外部,但它已硬编码到图像中,我将其作为图像编辑器的指南。

我尝试移动代码,我删除了行 ctx.clip() 并发现我的圆圈在图像顶部显示正常。

        // circle around avatar
        ctx.beginPath();
        ctx.arc(122.5, 141.8, 81, 0, Math.PI * 2, true);
        ctx.closePath();
        ctx.clip();
        const avatar = await Canvas.loadImage(
            message.author.displayAvatarURL({ format: 'png' })
        );
        ctx.strokeStyle = '#ffffff';
        ctx.strokeRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(avatar, 41.5, 60.5, 162, 162);

        // presence circle
        ctx.beginPath();
        ctx.arc(184.5, 193.5, 19, 0, Math.PI * 2, true);
        ctx.strokeStyle = '#000000';
        ctx.lineWidth = 8;
        ctx.stroke();
        ctx.fillStyle = userStatusColor;
        ctx.fill();

看看 canvas clip() 定义:
https://www.w3schools.com/tags/canvas_clip.asp

Tip: Once a region is clipped, all future drawing will be limited to the clipped region (no access to other regions on the canvas). You can however save the current canvas region using the save() method before using the clip() method, and restore it (with the restore() method) any time in the future.

下面是一个使用保存和恢复的例子

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

ctx.beginPath();
ctx.arc(90, 90, 81, 0, Math.PI * 2, true);
ctx.stroke();

ctx.save();
ctx.clip();

ctx.beginPath();
ctx.arc(150, 50, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#0000ff';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();

ctx.restore();

ctx.beginPath();
ctx.arc(170, 99, 19, 0, Math.PI * 2, true);
ctx.fillStyle = '#ff0000';
ctx.lineWidth = 8;
ctx.stroke();
ctx.fill();
<canvas id="canvas"></canvas>