Please bookmark this page to avoid losing your image tool!

Image Dashed Line Adder

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
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!

Description

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Image Tools:

Image To Dingbat Symbol Art Converter

Image Custom Polygon Cropper

Image Rule Of Thirds Grid Overlay Tool

Image Resizer for Social Media Platforms

Image Circular Crop Tool

Image Date Stamp Adder

Image Circular Guides Adder

Image Center Cropper

Image Petzval Lens Swirly Bokeh Effect Creator

Image Mimiya 645 Medium Format Filter Effect Tool

Photo Fujifilm Klasse W Filter Effect Application

Image Deardorff Large Format Filter Effect Application

Image Lomo LC-A Filter Effect Tool

Image Large Format Filter Effect Application

Image Zone Plate Lens Effect Creator

Photo Kodak Retina Filter Effect Tool

Image Polaroid 600 Filter Effect Tool

Photo Black and White Yellow Filter Effect Tool

Image Contax G2 Film Camera Render Effect Applicator

Image 110 Film Format Filter Effect Tool

Photo Jupiter-9 Portrait Lens Filter Effect

Image Fujifilm GW690 Texas Leica Filter Effect Application

Image Zeiss T* Coating Filter Effect Tool

Image Hoya R72 Infrared Filter Effect Tool

Image Filter Effect for Zeiss Ikon Contaflex

Photo Olympus Mju-II/Stylus Epic Filter Effect Tool

Image NiSi Nano IR ND Filter Effect Tool

Image Polaroid SX-70 Filter Effect Tool

Image Linhof Technika Filter Effect Tool

Image Lee Big Stopper 10-Stop ND Filter Effect Tool

Image Minolta X-700 Film Camera Render Effect Creator

Image ORWO UN54 Motion Picture Film Effect Applicator

Image Shen-Hao Large Format Filter Effect Tool

Image Impossible Project Polaroid Filter Effect Tool

Photo Foma Retropan 320 Film Filter Effect Tool

Image Fuji QuickSnap Disposable Filter Effect Application

See All →