Polygon with a hole in the middle with HTML5#39;s canvas(中间有洞的多边形,带有 HTML5 的画布)
问题描述
使用 <canvas>
标签我需要能够在多边形中绘制一个洞.
Using the <canvas>
tag I need to be able to draw a hole in a polygon.
现在我有一些非常简单的方法,它使用 beginPath() 然后为每个点执行 lineTo().然后用 fill() 填充.
Right now I have something very simple that uses beginPath() then does lineTo() for each point. It is then filled with fill().
我看不出有什么方法可以让一个填充的多边形中间没有填充,就像一个甜甜圈.我不是在做甜甜圈,但它适合这个例子.
I cannot see any way to have a filled polygon with a unfilled middle though, like a donut. I'm not making a donut but it is suitable for this example.
我有什么遗漏吗?我宁愿不把它画满,然后不得不重画中间.
Is there something I am missing? I would rather not draw it fully filled then have to redraw the middle.
推荐答案
这是我做的:
var ctx = canvas.getContext("2d");
ctx.beginPath();
//polygon1--- usually the outside polygon, must be clockwise
ctx.moveTo(0, 0);
ctx.lineTo(200, 0);
ctx.lineTo(200, 200);
ctx.lineTo(0, 200);
ctx.lineTo(0, 0);
ctx.closePath();
//polygon2 --- usually hole,must be counter-clockwise
ctx.moveTo(10, 10);
ctx.lineTo(10,100);
ctx.lineTo(100, 100);
ctx.lineTo(100, 10);
ctx.lineTo(10, 10);
ctx.closePath();
// add as many holes as you want
ctx.fillStyle = "#FF0000";
ctx.strokeStyle = "rgba(0.5,0.5,0.5,0.5)";
ctx.lineWidth = 1;
ctx.fill();
ctx.stroke();
这里的主要思想是你只能使用一次 beginPath;外部多边形必须是顺时针方向,孔必须是逆时针方向.
The main idea here is you can only use beginPath once; the outside polygon must be clockwise and holes must be counter-clockwise.
这篇关于中间有洞的多边形,带有 HTML5 的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:中间有洞的多边形,带有 HTML5 的画布


- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01