make a square image with a rectangle in the middle in javascript

To create a square image with a rectangle in the middle using JavaScript, you can use the HTML5 Canvas element. Here's a simple example to achieve this:

index.tsx
// Get the canvas element
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);

// Set canvas size
const size = 200;
canvas.width = size;
canvas.height = size;

// Get the 2d context for the canvas
const ctx = canvas.getContext('2d');

// Define square properties
const squareSize = 150;
const squareX = (size - squareSize) / 2;
const squareY = (size - squareSize) / 2;

// Draw the square
ctx.fillStyle = 'blue';
ctx.fillRect(squareX, squareY, squareSize, squareSize);

// Define rectangle properties
const rectWidth = 100;
const rectHeight = 50;
const rectX = (size - rectWidth) / 2;
const rectY = (size - rectHeight) / 2;

// Draw the rectangle
ctx.fillStyle = 'red';
ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
753 chars
31 lines

This code creates a square canvas with a blue square in the middle and a red rectangle in the middle of the square. You can customize the sizes and colors as needed.

related categories

gistlibby LogSnag