带有HTML5画布中间的孔的多边形 [英] Polygon with a hole in the middle with HTML5's canvas

查看:117
本文介绍了带有HTML5画布中间的孔的多边形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用< canvas> 标记我需要能够在多边形中绘制一个洞。



现在我有一件非常简单的事情,它使用beginPath(),然后为每个点执行lineTo()。然后填充fill()。



我看不出有什么方法可以填充一个填充的多边形,虽然中间没有填充,就像一个甜甜圈一样。
我没有做甜甜圈,但它适用于这个例子。



有什么我失踪了吗?
我宁愿不把它填满,然后重新绘制中间。

解决方案

这就是我所做的work:

  var ctx = canvas.getContext(2d); 
ctx.beginPath();

// polygon1 ---通常是外部多边形,必须是顺时针
ctx.moveTo(0,0);
ctx.lineTo(200,0);
ctx.lineTo(200,200);
ctx.lineTo(0,200);
ctx.lineTo(0,0);
ctx.closePath();

// polygon2 ---通常是孔,必须是逆时针
ctx.moveTo(10,10);
ctx.lineTo(10,100);
ctx.lineTo(100,100);
ctx.lineTo(100,10);
ctx.lineTo(10,10);
ctx.closePath();

//根据需要添加许多孔
ctx.fillStyle =#FF0000;
ctx.strokeStyle =rgba(0.5,0.5,0.5,0.5);
ctx.lineWidth = 1;
ctx.fill();
ctx.stroke();

这里的主要思想是您只能使用beginPath一次;外面的多边形必须是顺时针的,孔必须是逆时针的。

Using the <canvas> tag I need to be able to draw a hole in a polygon.

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.

解决方案

This is what i made it work:

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();

The main idea here is you can only use beginPath once; the outside polygon must be clockwise and holes must be counter-clockwise.

这篇关于带有HTML5画布中间的孔的多边形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆