javascript - 带圆角的画布 clearRect
问题描述
我已经用ctx.clearRect()
. 它在图像中生成一个矩形透明区域。但是有没有可能用圆角切掉它?
像这样:
我的代码:
function createHolesInBg() {
// overlay the image on the video and cut holes to see through to the video
var image = document.getElementById('bg-one');
var canvas = document.getElementById("window-canvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
window.setTimeout(function() {
ctx.clearRect(390, 150, 400, 300);
}, 0);
};
// show video for 5 seconds and then start to cut some holes overlay bg
window.setTimeout(function() {
createHolesInBg();
}, 0);
// mute the video after 15 seconds as its gets annoying in blog post
window.setTimeout(function() {
var video = document.getElementById("video-elm");
video.muted = false;
}, 0);
body {
background-color: #000;
margin: 0;
padding: 0;
}
#window-canvas { pointer-events: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- background video -->
<div stlye="position:absolute; top:0; left: 0;">
<video width="1180" height="620" controls autoplay loop id="video-elm">
<source src="https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_1mb.mp4">
Your browser does not support HTML5 video.
</video>
</div>
<!-- canvas layer -->
<canvas id="window-canvas" height="620" width="1280" style="position: absolute; top:0; left:0;"></canvas>
<!-- hidden foreground image for use by Canvas -->
<img src="https://i.pinimg.com/originals/0c/80/b6/0c80b6dfc2b311bac185c0b310bb18da.jpg" style="position: absolute; top:0; left:0; display:none;" id="bg-one">
解决方案
我在 Github 上找到了这段代码:https ://gist.github.com/getify/2926699
方法是先创建一个您想要的形状的剪切区域,然后再创建一个clearRect
包含整个剪切区域的剪切区域。
您可以在此处按照此示例代码了解如何创建圆角矩形:如何在 HTML Canvas 上绘制圆角矩形?
结合这两件事应该会给你你正在寻找的结果。
function clearRoundRect(context, x, y, width, height, radius) {
context.save();
context.beginPath();
roundRect(context, x, y, width, height, radius, false, true);
context.clip();
context.clearRect(x, y, width, height);
context.restore();
}
推荐阅读
- r - 如何根据是否满足特定条件在数据表中绘制信息?
- reactive-programming - RxSwift 中的 PublishSubject 和 PublishRelay 有什么区别?
- store - 高分辨率图标为 128px 但提交被拒绝
- javascript - 使用 Ajax 发送数据并在控制器中接收时出错
- ruby-on-rails - 未找到动作记录。找不到 id=
- wpf - 对话框应该在按钮单击时出现在前面
- java - 雪花集成测试实施
- ios - Swift - 从文档目录中删除自定义文件夹
- html - 如何从“检查元素”浏览器选项跨多个网页查找/查找特定字符串/选择器/XPath?
- react-native - 使用 GDrive.files.list({) 时找不到共享驱动器