RobotApp/RobotApp.Client/wwwroot/js/canvas.js
Đăng Nguyễn c5686e4ecf update
2025-10-03 11:31:14 +07:00

107 lines
2.5 KiB
JavaScript

window.getElementSize = (element) => {
return {
width: element.clientWidth,
height: element.clientHeight,
};
}
window.getElementBoundingRect = (element) => {
const rect = element.getBoundingClientRect();
return {
width: rect.width,
height: rect.height,
x: rect.x,
y: rect.y,
left: rect.left,
top: rect.top
};
}
window.setCanvasSize = (canvas, width, height) => {
canvas.width = width;
canvas.height = height;
}
window.imageCache = new Map();
window.preloadImage = (imagePath) => {
return new Promise((resolve, reject) => {
if (window.imageCache.has(imagePath)) {
resolve(window.imageCache.get(imagePath));
return;
}
const img = new Image();
img.onload = () => {
window.imageCache.set(imagePath, img);
resolve(img);
};
img.onerror = () => {
reject(new Error(`Failed to load image: ${imagePath}`));
};
img.src = imagePath;
});
};
window.preloadImageFromUrl = (url, cacheKey) => {
return new Promise((resolve, reject) => {
if (window.imageCache.has(cacheKey)) {
resolve(window.imageCache.get(cacheKey));
return;
}
const img = new Image();
img.onload = () => {
window.imageCache.set(cacheKey, img);
resolve(img);
};
img.onerror = (error) => {
reject(new Error(`Failed to load image from URL: ${url}`));
};
img.src = url;
});
};
window.getImageDimensions = (cacheKey) => {
const img = window.imageCache.get(cacheKey);
if (!img) {
return { width: 0, height: 0 };
}
return {
width: img.naturalWidth || img.width,
height: img.naturalHeight || img.height
};
};
window.drawImageOnCanvas = (canvas, imagePath, x, y, width, height) => {
const ctx = canvas.getContext('2d');
const img = window.imageCache.get(imagePath);
if (!img) {
return false;
}
try {
ctx.drawImage(img, x, y, width, height);
return true;
} catch (error) {
return false;
}
};
window.drawCachedImageOnCanvas = (canvas, cacheKey, x, y, width, height) => {
const ctx = canvas.getContext('2d');
const img = window.imageCache.get(cacheKey);
if (!img) {
return false;
}
try {
ctx.drawImage(img, x, y, width, height);
return true;
} catch (error) {
return false;
}
};