I also asked ChatGPT for a solution. It looks nice but know that I have not tested this.
Q:
in html and javascript. How can I draw a polygon over an image. I do not want to use jQuery, only pure javascript. I know the coordingates of the corners as a percentage of the dimensions of the image
A:
You can draw a polygon over an image using HTML and pure JavaScript by following these steps:
- Create an HTML element to hold the image and the polygon. For example:

- Get the dimensions of the image and calculate the coordinates of the polygon corners based on the percentage values. For example:
var image = document.getElementById('image');
var container = document.getElementById('imageContainer');
var polygon = document.getElementById('polygon');
var ctx = polygon.getContext('2d');
var imageWidth = image.clientWidth;
var imageHeight = image.clientHeight;
// Define the polygon coordinates as percentages of the image dimensions
var polygonPoints = [
{ x: 0.2, y: 0.1 }, // Example corner point
{ x: 0.5, y: 0.3 }, // Example corner point
// Add more corner points as needed
];
// Calculate the polygon coordinates relative to the container dimensions
var containerWidth = container.clientWidth;
var containerHeight = container.clientHeight;
var polygonCoordinates = polygonPoints.map(function(point) {
return {
x: point.x * containerWidth,
y: point.y * containerHeight,
};
});
- Draw the polygon on the canvas using the calculated coordinates. For example:
// Set the canvas size to match the container dimensions
polygon.width = containerWidth;
polygon.height = containerHeight;
// Clear the canvas
ctx.clearRect(0, 0, polygon.width, polygon.height);
// Draw the polygon
ctx.beginPath();
ctx.moveTo(polygonCoordinates[0].x, polygonCoordinates[0].y);
for (var i = 1; i < polygonCoordinates.length; i++) {
ctx.lineTo(polygonCoordinates[i].x, polygonCoordinates[i].y);
}
ctx.closePath();
ctx.fillStyle = 'rgba(255, 0, 0, 0.5)'; // Example fill color with transparency
ctx.fill();
ctx.strokeStyle = 'red'; // Example stroke color
ctx.lineWidth = 2; // Example stroke width
ctx.stroke();
By following these steps, you should be able to draw a polygon over an image using pure JavaScript. Adjust the code as needed to suit your specific use case.