You can edit the below JavaScript code to customize the image tool.
function processImage(originalImg, lineColor = "#000000", lineWidth = 2, dashPatternStr = "5,5", startX = 10, startY = 10, endX, endY) {
// Helper function to create a styled error message element
function createErrorElement(message) {
const errorElement = document.createElement('div');
errorElement.textContent = message;
// Basic styling for the error message
errorElement.style.color = '#D8000C'; // Red text
errorElement.style.backgroundColor = '#FFD2D2'; // Light red background
errorElement.style.border = '1px solid #D8000C';
errorElement.style.padding = '10px';
errorElement.style.margin = '10px';
errorElement.style.fontFamily = 'Arial, sans-serif';
return errorElement;
}
// --- Input Validations ---
if (!(originalImg instanceof HTMLImageElement)) {
console.error("Parameter 'originalImg' must be an HTMLImageElement.");
return createErrorElement("Error: originalImg must be an HTMLImageElement.");
}
// --- Image Loading and Dimensions ---
// We assume the image is loaded. If not, naturalWidth/Height will be 0.
// For a robust solution with unloaded images, processImage would need to be async
// and await originalImg.decode() or use originalImg.onload.
// Given the synchronous signature implied by default guideline, proceeding with current state.
// If image is not loaded (naturalWidth/Height = 0), a 0x0 canvas will be created.
const imgWidth = originalImg.naturalWidth;
const imgHeight = originalImg.naturalHeight;
// --- Canvas Setup ---
const canvas = document.createElement('canvas');
canvas.width = imgWidth;
canvas.height = imgHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error("Failed to get 2D context from canvas.");
return createErrorElement("Error: Canvas 2D context is not supported or failed to initialize.");
}
// --- Draw Original Image ---
if (imgWidth > 0 && imgHeight > 0) {
try {
ctx.drawImage(originalImg, 0, 0, imgWidth, imgHeight);
} catch (e) {
// This can happen due to various reasons, e.g., CORS issues with tainted canvases.
console.error("Error drawing originalImg to canvas:", e);
// Provide visual feedback on the canvas about the error
ctx.fillStyle = "rgba(230, 230, 230, 0.8)"; // Light gray semi-transparent overlay
ctx.fillRect(0, 0, imgWidth, imgHeight);
ctx.fillStyle = "#D8000C"; // Red text color
ctx.font = "bold 16px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText("Error displaying image.", imgWidth / 2, imgHeight / 2 - 10);
ctx.font = "12px Arial";
ctx.fillText("Dashed line will be drawn over this placeholder.", imgWidth/2, imgHeight/2 + 10);
// Continue to draw the line even if the image fails to draw.
}
} else {
// If imgWidth or imgHeight is 0, the canvas has zero area in one or both dimensions.
// Drawing will likely have no visible effect.
console.warn(`Image dimensions are ${imgWidth}x${imgHeight}. Dashed line may not be visible.`);
}
// --- Parameter Processing for Line ---
// Determine actual end coordinates for the line.
// If endX/endY are not provided (undefined), default them.
// If image dimension is 0, line defaults to 0-length at startX, startY.
// Otherwise, default to 10px from the edge, ensuring non-negative coord.
const actualEndX = (endX === undefined)
? (imgWidth > 0 ? Math.max(0, imgWidth - 10) : startX)
: endX;
const actualEndY = (endY === undefined)
? (imgHeight > 0 ? Math.max(0, imgHeight - 10) : startY)
: endY;
// Parse the dash pattern string (e.g., "5,5" or "10,3,2,3")
let dashArray;
if (dashPatternStr && typeof dashPatternStr === 'string' && dashPatternStr.trim() !== "") {
dashArray = dashPatternStr.split(',')
.map(s => parseFloat(s.trim()))
.filter(n => !isNaN(n) && n >= 0); // Dash/gap lengths must be non-negative.
if (dashArray.length === 0) {
// Fallback if parsing results in empty array (e.g., "abc,def" or only negative numbers like "-1,-5")
console.warn(`Invalid or empty dashPatternStr: "${dashPatternStr}". Using default pattern [5,5]. Ensure dash/gap lengths are non-negative.`);
dashArray = [5, 5];
}
// Note: If dashArray contains only zeros (e.g., [0,0]), setLineDash([0,0]) typically results in a solid line.
} else {
// Default pattern if input is an empty string, null, or undefined (though handled by param default)
dashArray = [5, 5];
}
// --- Line Drawing ---
ctx.beginPath();
// lineWidth: HTML Canvas standard specifies that 0, negative, Infinity, NaN are ignored,
// meaning lineWidth effectively remains unchanged or defaults to 1.0.
// We pass the user-provided lineWidth directly. Default is 2.
ctx.lineWidth = lineWidth;
ctx.strokeStyle = lineColor;
// Set the dash pattern.
if (typeof ctx.setLineDash === 'function') {
// Ensure dashArray has elements. If it was e.g. "0" filtered to [0], it's valid.
// If dashArray is empty (e.g. from invalid input like "foo") it would have defaulted to [5,5] above.
ctx.setLineDash(dashArray);
} else {
// Fallback for very old browsers (e.g., IE < 11) that don't support setLineDash.
// The line will be solid.
console.warn("CanvasRenderingContext2D.setLineDash() is not supported. Drawing a solid line instead.");
}
ctx.moveTo(startX, startY);
ctx.lineTo(actualEndX, actualEndY);
ctx.stroke();
// Good practice: reset dash pattern to solid for any subsequent drawing operations on this context
// (though here the context is part of the returned canvas and not reused by this function).
if (typeof ctx.setLineDash === 'function') {
ctx.setLineDash([]);
}
return canvas;
}
Free Image Tool Creator
Can't find the image tool you're looking for? Create one based on your own needs now!
The Image Dashed Line Adder tool allows users to add customizable dashed lines to images. Users can specify line color, width, dash pattern, and start and end coordinates for the line. This tool is useful for creating visual guides, annotations, or overlays on images in various contexts, such as graphic design, presentations, educational materials, and document editing.