画布多边形边框被裁剪

当我将线宽设置为大于 1 时,线会显示为裁剪。考虑到定义的线宽,我想知道如何在画布尺寸中显示多边形而不被裁剪。提前致谢!


var c = document.getElementById("myCanvas");

var ctx = c.getContext("2d");

var polygon = [

  {x: 178, y: 160}, {x: 124, y: 0}, {x: 265, y: 88},

  {x: 382, y: 0}, {x: 393, y: 118}, {x: 770, y: 178},

  {x: 479, y: 221}, {x: 441, y: 228}, {x: 579, y: 376},

  {x: 309, y: 314}, {x: 197, y: 428}, {x: 183, y: 304},

  {x: 0, y: 324}, {x: 132, y: 240}, {x: 36, y: 152}

];


ctx.strokeStyle = "rgba(46, 139, 86, 1.00)";

ctx.fillStyle = "rgba(156, 205, 50, 1.00)";

ctx.lineWidth = 9;


ctx.beginPath();

ctx.moveTo(polygon[0].x, polygon[0].y);

for( var i = 1; i<polygon.length; i++){

    ctx.lineTo(polygon[i].x, polygon[i].y);

}

ctx.closePath();

ctx.stroke();

ctx.fill();

<canvas id="myCanvas" width="770" height="428" style="border:1px solid #d3d3d3;">

</canvas>


红颜莎娜
浏览 82回答 1
1回答

一只斗牛犬

所以你想把它保持在画布的范围内?如果是这样,您可以使用clip然后将电流加倍lineWidth并在该点填充/抚摸来实现它,这使其保持在画布的边界内。默认剪辑算法不允许点在其外部填充,这使其始终适用于画布边界。下面的例子。var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");var polygon = [&nbsp; {x: 178, y: 160}, {x: 124, y: 0}, {x: 265, y: 88},&nbsp; {x: 382, y: 0}, {x: 393, y: 118}, {x: 770, y: 178},&nbsp; {x: 479, y: 221}, {x: 441, y: 228}, {x: 579, y: 376},&nbsp; {x: 309, y: 314}, {x: 197, y: 428}, {x: 183, y: 304},&nbsp; {x: 0, y: 324}, {x: 132, y: 240}, {x: 36, y: 152}];ctx.strokeStyle = "rgba(46, 139, 86, 1.00)";ctx.fillStyle = "rgba(156, 205, 50, 1.00)";const lineWidth = 9;ctx.lineWidth = lineWidth;ctx.beginPath();ctx.moveTo(polygon[0].x, polygon[0].y);for( var i = 1; i<polygon.length; i++){&nbsp; ctx.lineTo(polygon[i].x, polygon[i].y);}ctx.closePath();ctx.save();ctx.clip();ctx.lineWidth *= 2;ctx.fill();ctx.stroke();ctx.restore();<canvas id="myCanvas" width="770" height="428" style="border:1px solid #d3d3d3;"></canvas>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript