I'm working on a snake game in JavaScript and the Phaser3 framework, and I want to draw a pill shaped line to use for the snake. So I want to draw rounded line segments filled with one color (green) and outlined with another color (black). It is not one straight line, but rather several connected line segments. They are all connected at right angles, so 0, 90, 180 or 270 degrees.
See the mock up image below.
Here is my code to draw a line, there is an array with the grid locations of line segments positions:
var TILE_SIZE = 32;
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// points of each snake segment
snake_segs = [ [9, 11], [10, 11], [10, 12], [11, 12], [11, 13], [12, 13], [12, 12] ];
// set line color
ctx.strokeStyle = "#FFFF00";
ctx.beginPath();
// draw all line segments
for (var i = 0; i < snake_segs.length-1; i++) {
var xpos1 = snake_segs[i][0] * TILE_SIZE;
var ypos1 = snake_segs[i][1] * TILE_SIZE;
var xpos2 = snake_segs[i+1][0] * TILE_SIZE;
var ypos2 = snake_segs[i+1][1] * TILE_SIZE;
ctx.moveTo(xpos1, ypos1);
ctx.lineTo(xpos2, ypos2);
}
ctx.stroke();
How to turn this into a rounded pill shaped line?
What is the best approach to do this? This is harder than I initially thought. Is there an algorithm to draw a pill shaped outline? Or is there a clever way to using rounded rectangles that overlap? Or is it best to draw the outline in a clock-wise fashion? But then how do you find the shape of that outline?
