javascript 带圆角的 HTML5 Canvas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15007903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:08:16  来源:igfitidea点击:

HTML5 Canvas with rounded corner

javascripthtmlcsscanvasrounded-corners

提问by alexmngn

I'd like to have an HTML5 canvas with rounded corner. I'm using the CSS property border-radius: 15pxto round my corners.

我想要一个带圆角的 HTML5 画布。我正在使用 CSS 属性border-radius: 15px来绕过我的角落。

But, when I draw something in the corner of my canvas, I can draw in the corner.

但是,当我在画布的角落里画东西时,我可以在角落里画画。

At the beginning:

一开始:

What I have:

我有的:

What I want:

我想要的是:

enter image description here

在此处输入图片说明

Do you have any solution to avoid that? I thought about create a mask but I don't really know how to do.. For information, this works on Firefox but not on Chrome/Safari/Opera.

你有什么解决办法来避免这种情况吗?我想过创建一个蒙版,但我真的不知道该怎么做。有关信息,这适用于 Firefox,但不适用于 Chrome/Safari/Opera。

This is a small example:

这是一个小例子:

http://jsfiddle.net/XYHpJ/

http://jsfiddle.net/XYHpJ/

Thanks!

谢谢!

回答by Tommy S?rensen

Just use this example on stackoverflow: https://stackoverflow.com/a/12336233/1312570

只需在 stackoverflow 上使用此示例:https: //stackoverflow.com/a/12336233/1312570

Solution: http://jsfiddle.net/rzSmw/

解决方案: http://jsfiddle.net/rzSmw/

#canvas_container
{
    background: #fff;
    border: 1px solid #aaa;
    border-radius: 15px;
    height: 515px;
    margin: 20px 20px;
    overflow: hidden;
    width: 690px;

    /* this fixes the overflow:hidden in Chrome/Opera */
    -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
}

回答by Nathan Campos

The best way to avoid that is by inserting the <canvas>inside a "container" tag and then apply the border-radiusto the container. Like this:

避免这种情况的最佳方法是在<canvas>内部插入“容器”标签,然后将其应用border-radius到容器。像这样:

<div id="container">
    <canvas></canvas>
</div>

With this CSS:

使用这个 CSS:

#container {
    border-radius: 10px;
    background-color: white;
    border: 1px solid #000;
    overflow: hidden;
}

#container > div {
    height: 200px;
    background-color: red;
}

A working example: http://jsbin.com/onuqid/2/

一个工作示例:http: //jsbin.com/onuqid/2/

You can also use display: block;and get rid of the wrapper as Allendarsuggested in the comments.

您还可以display: block;按照Allendar在评论中的建议使用和摆脱包装器。