ملف العمل الأصلي
tools/export.js
تحتفظ الشيفرة وصفحات الأمثلة القابلة للتشغيل بمعرّفاتها ونصوصها التجريبية الأصلية. يشرحها الدرس وإرشادات الملفات بلغتك.
let selected = null,
previewURL;
const status = document.querySelector("[role=status]"),
preview = document.querySelector("#source-preview");
function select(file) {
selected = file;
if (previewURL) URL.revokeObjectURL(previewURL);
previewURL = URL.createObjectURL(file);
preview.src = previewURL;
preview.hidden = false;
status.textContent =
"Ready: " + file.name + " (" + file.size + " bytes). Choose 480 or 960, then export.";
}
document.querySelector("#sample").addEventListener("click", async () => {
try {
const response = await fetch("../before/photo-full.webp");
if (!response.ok) throw Error();
select(new File([await response.blob()], "photo-full.webp", { type: "image/webp" }));
} catch {
status.textContent =
"Open this tool from the lesson, or serve the extracted workshop over localhost. You can also select the supplied before/photo-full.webp file.";
}
});
document.querySelector("[type=file]").addEventListener("change", (e) => {
if (e.target.files[0]) select(e.target.files[0]);
});
document.querySelector("#export").addEventListener("click", async () => {
const f = selected,
w = Number(document.querySelector("[type=number]").value);
if (
!f ||
!["image/png", "image/jpeg", "image/webp"].includes(f.type) ||
f.size > 10000000 ||
!Number.isInteger(w) ||
w < 100 ||
w > 2000
) {
status.textContent = "Select the supplied image and a width from 100 to 2000.";
return;
}
try {
const image = await createImageBitmap(f),
canvas = document.createElement("canvas");
canvas.width = Math.min(w, image.width);
canvas.height = Math.round((image.height * canvas.width) / image.width);
canvas.getContext("2d").drawImage(image, 0, 0, canvas.width, canvas.height);
image.close();
canvas.toBlob(
(blob) => {
if (!blob) {
status.textContent = "Export failed";
return;
}
const a = document.createElement("a"),
url = URL.createObjectURL(blob);
a.href = url;
a.download =
"photo-" + canvas.width + (blob.type === "image/webp" ? ".webp" : ".png");
a.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
status.textContent =
"Exported " + canvas.width + " pixels, " + blob.size + " bytes.";
},
"image/webp",
0.82,
);
} catch {
status.textContent = "Could not decode this image.";
}
});