webtools/site/gradient-image/main.js

71 lines
2.1 KiB
JavaScript
Raw Normal View History

2026-03-12 11:52:25 +00:00
const PREVIEW_SIZE = 256;
const fromColorEl = document.getElementById("from-color");
const toColorEl = document.getElementById("to-color");
const gradientTypeEl = document.getElementById("gradient-type");
const rotationEl = document.getElementById("rotation");
const rotationValueEl = document.getElementById("rotation-value");
const imageSizeEl = document.getElementById("image-size");
const canvas = document.getElementById("preview-canvas");
const downloadBtn = document.getElementById("download-btn");
function drawGradient(ctx, size) {
const fromColor = fromColorEl.value;
const toColor = toColorEl.value;
const type = gradientTypeEl.value;
const rotation = parseInt(rotationEl.value);
const cx = size / 2;
const cy = size / 2;
let gradient;
if (type === "radial") {
const radius = size / 2;
gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
} else {
const angle = (rotation * Math.PI) / 180;
const len = size / 2;
const dx = Math.cos(angle) * len;
const dy = Math.sin(angle) * len;
gradient = ctx.createLinearGradient(cx - dx, cy - dy, cx + dx, cy + dy);
}
gradient.addColorStop(0, fromColor);
gradient.addColorStop(1, toColor);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
}
function renderPreview() {
canvas.width = PREVIEW_SIZE;
canvas.height = PREVIEW_SIZE;
const ctx = canvas.getContext("2d");
drawGradient(ctx, PREVIEW_SIZE);
}
function download() {
const size = parseInt(imageSizeEl.value);
const offscreen = document.createElement("canvas");
offscreen.width = size;
offscreen.height = size;
const ctx = offscreen.getContext("2d");
drawGradient(ctx, size);
const link = document.createElement("a");
link.download = `gradient-${size}x${size}.png`;
link.href = offscreen.toDataURL("image/png");
link.click();
}
fromColorEl.addEventListener("input", renderPreview);
toColorEl.addEventListener("input", renderPreview);
gradientTypeEl.addEventListener("input", renderPreview);
rotationEl.addEventListener("input", () => {
rotationValueEl.textContent = rotationEl.value;
renderPreview();
});
downloadBtn.addEventListener("click", download);
renderPreview();