首页 > 解决方案 > 重叠剪裁问题

问题描述

我有一个问题,我要抓住一个用户displayAvatar(),然后我使用弧线使图像变圆。这很好用,但是,我需要在该图像上放置一个圆圈,但由于之前的原因,它被切成了两半clip()

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

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

我知道在“使用剪辑()”图像中,弧形边框似乎显示在剪辑之外,但这是硬编码到图像中的,我将其作为图像编辑器的指南。

我试着移动代码,我删除了这条线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();

标签: javascriptnode.jscanvasdiscord.jsnode-canvas

解决方案


看一下画布 clip() 定义:
https ://www.w3schools.com/tags/canvas_clip.asp

提示:一旦某个区域被剪裁,以后的所有绘图都将被限制在剪裁区域内(无法访问画布上的其他区域)。但是,您可以在使用 clip() 方法之前使用 save() 方法保存当前画布区域,并在将来的任何时间恢复它(使用 restore() 方法)。

下面是使用保存和恢复的示例

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>


推荐阅读