David R
David R

Reputation: 449

Canvas polygon border is cropped

When I set a line width higher than 1, the line is displayed cropped. I would like to know how can I display the polygon in that canvas dimensions without being cropped, considering the defined line width. Thanks in advance!

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>

Upvotes: 0

Views: 375

Answers (1)

Loktar
Loktar

Reputation: 35309

So you're trying to keep it within the bounds of the canvas? If so you can acheive it using clip then doubling the current lineWidth and filling/stroking at that point, which keeps it within the boundaries of the canvas. The default clip algorithm wont allow points to fill outside of it which allows this to always work for canvas boundaries.

Example below.

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

const lineWidth = 9;
ctx.lineWidth = lineWidth;

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.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>

Upvotes: 1

Related Questions