将 Javascript 画布形状限制到指定区域

问题描述 投票:0回答:1

有没有办法将文本、矩形和其他形状/元素约束到 JavaScript 中的指定矩形?我正在构建一个在另一个项目中使用的工具,我想绘制一个较小的窗口,其中包含文本,并让该窗口覆盖其他所有内容。但是,我也希望文本(以及内部的任何其他元素)无法流出窗口。

我尝试先绘制这个内部窗口和内部的元素,以便覆盖其上的所有其他元素,但这不起作用,因为其他元素遮挡了较小窗口内的项目,而不是仅仅覆盖了外部的部分。有内置的方法可以做到这一点吗?感谢大家

javascript canvas html5-canvas
1个回答
0
投票

如果你想在画布上模仿窗口,则需要实现“多边形裁剪”,窗口内的所有内容都会显示出来,超出窗口边界的内容都会被剪掉。

您需要 clip() 方法

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

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// Set the clipping rectangle
const windowX = 50;
const windowY = 50;
const windowWidth = 100;
const windowHeight = 200;

// before clippings
ctx.strokeStyle = "green";
ctx.strokeRect(windowX, windowY, windowWidth, windowHeight);

// Create a rectangle path
ctx.beginPath();
ctx.rect(windowX, windowY, windowWidth, windowHeight);

// Clip the canvas to the specified rectangle
ctx.clip();
ctx.closePath();

// Draw on the clipped area
// Example: draw a circle
ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
© www.soinside.com 2019 - 2024. All rights reserved.