create icons in javascript

There are different ways to create icons in JavaScript. Two popular approaches are using SVG and creating icons programmatically using the Canvas API.

SVG Icons

SVG stands for Scalable Vector Graphics and is an XML-based vector image format that can be scaled without losing quality. Creating icons using SVG is a popular approach because SVG is easy to manipulate using JavaScript and can be styled using CSS. Here's an example of how to create an SVG icon using JavaScript:

index.tsx
const svgns = "http://www.w3.org/2000/svg";
const svgIcon = document.createElementNS(svgns, "svg");
svgIcon.setAttributeNS(null, "viewBox", "0 0 24 24");

const path = document.createElementNS(svgns, "path");
path.setAttributeNS(null, "d", "M12 2L3 22h18L12 2z");

svgIcon.appendChild(path);
document.body.appendChild(svgIcon);
328 chars
10 lines

The code above creates an SVG icon that looks like a triangle with sharp edges. The M, L, and z in the d attribute of the <path> element represent the commands to draw the path.

Canvas Icons

The Canvas API is a powerful way of programmatically drawing graphics using JavaScript. Creating icons using the Canvas API is useful when you need to create complex or dynamic graphics. Here's an example of how to create a Canvas icon using JavaScript:

index.tsx
const canvas = document.createElement("canvas");
canvas.width = 24;
canvas.height = 24;
document.body.appendChild(canvas);

const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(12, 2);
ctx.lineTo(3, 22);
ctx.lineTo(21, 22);
ctx.closePath();
ctx.fillStyle = "red";
ctx.fill();
288 chars
14 lines

The code above creates a Canvas icon that looks like a triangle with rounded edges. The moveTo(), lineTo(), and closePath() functions are used to draw the path, and the fillStyle property sets the color to red.

related categories

gistlibby LogSnag