您有 2 种选择来使用 HTML5 画布绘制孔。
选择 1:
绘制不同时钟方向的外部形状和内部形状。
外部形状顺时针,内部形状逆时针。
或者外部形状顺时针,内部形状逆时针。
ctx.beginPath();
//outer shape, clockwise
ctx.moveTo(100,20);
ctx.lineTo(200,200);
ctx.lineTo(20,200);
ctx.closePath();
//inner shape (hole), counter-clockwise
ctx.moveTo(100,100);
ctx.lineTo(70,170);
ctx.lineTo(140,170);
ctx.closePath();
//fill
ctx.fillStyle = "#FF0000";
ctx.fill();
我们在编码的时候检测形状绘制方向有点痛苦。
如果你需要检测一系列点是否顺时针,这里有一个很好的功能:
function isClockwise(dots){
var sum = 0;
for(var i=1, n=dots.length; i<n; i++){
sum += (dots[i][0] - dots[i-1][0]) * (dots[i][1] + dots[i-1][1]);
}
sum += (dots[0][0] - dots[n-1][0]) * (dots[0][1] + dots[n-1][1]);
return sum < 0;
}
console.log(isClockwise([[100,20], [200,200], [20,200]])); //true
console.log(isClockwise([[100,20], [20,200], [200,200]])); //false
如果你的点是顺时针的,但你需要逆时针,.reverse() 你的点数组。
var dots = [[100,20], [200,200], [20,200]];
dots.reverse();
选择 2:
使用“偶数”填充规则,向任何方向绘制形状。
这种方式比选择1简单多了。
见fill() method API:
void ctx.fill();
void ctx.fill(fillRule);
void ctx.fill(path, fillRule);
fillRule 可以是 "nonzero" 或 "evenodd"
"nonzero":非零缠绕规则,默认规则。
“evenodd”:奇偶缠绕规则。
ctx.beginPath();
//outer shape, any direction, this sample is clockwise
ctx.moveTo(100,20);
ctx.lineTo(200,200);
ctx.lineTo(20,200);
ctx.closePath();
//inner shape (hole), any direction, this sample is clockwise
ctx.moveTo(100,100);
ctx.lineTo(140,170);
ctx.lineTo(70,170);
ctx.closePath();
//fill
ctx.fillStyle = "#FF0000";
ctx.mozFillRule = 'evenodd'; //for old firefox 1~30
ctx.fill('evenodd'); //for firefox 31+, IE 11+, chrome