JSFiddle - React, Tailwind, and code Playground
HTML
<div class="box">
<div class="text"></div>
<canvas class="rect-canvas"></canvas>
</div>
CSS
:root {
--x: 150px;
--y: 100px;
--w: 300px;
--h: 200px;
--r: 10px;
}
.box {
position: relative;
width: 600px;
height: 400px;
margin-bottom: 10px;
overflow: hidden;
background: #fff;
}
.rect-canvas {
position: absolute;
top: 0; left: 0;
}
JavaScript
const textElem = document.querySelectorAll('.text')
textElem.forEach(item => {
item.textContent = '测试文字'.repeat(176)
})
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath()
ctx.moveTo(x + r, y)
ctx.arcTo(x + w, y, x + w, y + h, r)
ctx.arcTo(x + w, y + h, x, y + h, r)
ctx.arcTo(x, y + h, x, y, r)
ctx.arcTo(x, y, x + w, y, r)
ctx.closePath()
}
const canvas = document.querySelector('canvas')
const ctx = canvas.getContext('2d')
const sw = canvas.parentNode.offsetWidth
const sh = canvas.parentNode.offsetHeight
canvas.width = sw
canvas.height = sh
ctx.fillStyle = 'rgba(0, 0, 0, .5)'
ctx.fillRect(0, 0, sw, sh)
ctx.beginPath()
roundRect(ctx, 150, 100, 300, 200, 10)
ctx.moveTo(370, 300)
ctx.lineTo(385, 315)
ctx.lineTo(400, 300)
ctx.clip()
ctx.clearRect(0, 0, sw, sh)