<canvas id="game" />
body {
margin: 0;
}
#game {
background-color: #222;
width: 100%;
height: 100%;
}
// Reference to the canvas instance
const canvas = document.getElementById("game");
const context = canvas.getContext("2d");
// Set the canvas dimensions to match that of the screen
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Draw a black rectangle to fill the entire canvas
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
// --- Plot the ship ---
// Define the points of the ship
const shipPoints = [
[1, 0],
[-0.714, 0.571],
[-0.429, 0.286],
[-0.429, -0.286],
[-0.714, -0.571]
];
// Keep track of the smallest screen dimension. This is
// used to prevent drawing the ship off the edge of the display
const squareSize = Math.min(canvas.width, canvas.height);
// Tell the context we want to begin a path
context.beginPath();
shipPoints
// Scale the ship to half the size of the screen
.map(([x, y]) => [x * squareSize / 4, y * squareSize / 4])
// Position the ship in the center of the screen
.map(([x, y]) => [x + canvas.width / 2, y + canvas.height / 2])
// Draw the points
.forEach(([x, y], index) => {
// If this is the first point, move the pen to that location
if (index === 0) {
context.moveTo(x, y);
return;
}
// Else draw a line from the previous location to the current
context.lineTo(x, y);
})
// Join the path back to the first point
context.closePath();
// Set the context stroke style to white
context.strokeStyle = "white";
// Draw the line
context.stroke();
// Clip off content outside of square
if (canvas.width > canvas.height) {
context.clearRect(
0,
0,
(canvas.width - canvas.height) / 2,
canvas.height
);
context.clearRect(
canvas.width - ((canvas.width - canvas.height) / 2),
0,
(canvas.width - canvas.height) / 2,
canvas.height
);
} else {
context.clearRect(
0,
0,
canvas.width,
(canvas.height - canvas.width) / 2
);
context.clearRect(
0,
canvas.height - ((canvas.height - canvas.width) / 2),
canvas.width,
(canvas.height - canvas.width) / 2
);
}
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.