在一个区域里取一个点,并向外引一条射线。这条射线会与组成这个区域的线条相交。而区域的线条都是有方向的,假设射线与一个方向的线条相交为+1,与另一个方向相交为-1。如果射线与所有方向的相交的结果的和为非0,则射线的起始点处于多边形的里面;如果为0,则处于多边形的外面
一般地,很少会绘制上图中无规律的图形。但是,在绘制空心图形,如圆环等,非零环绕原则也是适用的
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="canvas" height="80" width="80">当前浏览器不支持canvas,请更换浏览器后再试</canvas> <script> var canvas = document.getElementById('canvas'); var H = 80,W=80; if(canvas.getContext){ var cxt = canvas.getContext('2d'); cxt.beginPath(); cxt.arc(40,40,30,0,Math.PI*2,false); cxt.arc(40,40,15,0,Math.PI*2,true); cxt.fillStyle = '#058'; cxt.shadowColor = 'gray'; cxt.shadowOffsetX = 3; cxt.shadowOffsetY = 3; cxt.shadowBlur = 3; cxt.fill(); } </script> </body> </html>
接下来,利用非零环绕原则和阴影来绘制一个镂空的剪纸效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="drawing" style="border:1px solid black"> <p>The canvas element is not supported!</p> </canvas> <script> var canvas = document.getElementById('drawing'); if(drawing.getContext){ var cxt = drawing.getContext('2d'); cxt.fillStyle = "#FFF"; cxt.fillRect(0,0,300,150); cxt.beginPath(); cxt.rect(0,0,300,150); drawPathRect(cxt, 10, 10, 200, 80); drawPathTriangle(cxt, 10, 140,30, 100, 50, 140); cxt.arc(150, 120, 20, 0, Math.PI * 2, true); cxt.closePath(); cxt.fillStyle = "#058"; cxt.shadowColor = "gray"; cxt.shadowOffsetX = 10; cxt.shadowOffsetY = 10; cxt.shadowBlur = 10; cxt.fill(); //逆时针绘制矩形 function drawPathRect(cxt, x, y, w, h){ cxt.moveTo(x, y); cxt.lineTo(x, y + h); cxt.lineTo(x + w, y + h); cxt.lineTo(x + w, y); cxt.lineTo(x, y); } //逆时针绘制三角形 function drawPathTriangle(cxt, x1, y1, x2, y2, x3, y3){ cxt.moveTo(x1,y1); cxt.lineTo(x3,y3); cxt.lineTo(x2,y2); cxt.lineTo(x1,y1); } } </script> </body> </html>
原文链接:https://www.qiquanji.com/post/7888.html
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
微信扫码关注
更新实时通知