My goal is to make manipulations to an image by adding shapes on top of the image using JavaScript.

For example, adding rectangular shapes to an image of a refregirator, as shown below:


<!DOCTYPE html>
        #avaliableSpace {
            border-radius: 25px;
            background: #00B050;
            padding: 20px;
            width: 125px;
            height: 75px;

    <img src="http://imageshack.com/refrigerator.png" alt="Kitchen Refrigerator" style="width:1600px;height:1200px;">

    <p id="avaliableSpace"> </p>


I was able to get image to show up using a url link, but the rectangular shape is not overlaying on top of the image, rather appears below the image. I don't know what to do to make the rectangular shape to append to the image. I tried specifying x and y coordinates within the #avaliableSpace code block, but that didn't work.

Edited by Start4me: Grammar edit

9 Months
Discussion Span
Last Post by Taywin

You need to set z-index in CSS to be higher than the image you want to overlay. IIRC, the default z-index value for all HTML objects is 0. Add something like z-index: 99 to your CSS and see what happen.

Edited by Taywin


I'd recommend to set the fridge image as a background-image to an HTML element such as a div that will have the same dimensions as the image.
Then you can nest other div tags within that div for your shapes and position them with floats and margins or with flexbox if you don't care about IE9 and below :) where you want them.

Edited by gentlemedia


I was able to resolve my issue using canvas. However, I'm trying to export an image that has the image (fridge as the background) with the filled rectangeles (overlays), but I'm only able to save the overlaying rectangles. How would I merge/combine the image with the rectangles and export to save as image?

// image that goes to the background
<img id='theImg' src='http://imageshack.com/refrigerator.png'>
// canvas for creating rectangles that go on top of the image
<canvas id='myCanvas' width='600' height='1000'></canvas>

var cnvs = document.getElementById("myCanvas");
var ctx = cnvs.getContext("2d");
// place the rectangles at the specified coordinates and dimensions
ctx.fillRect(xCor, yCor, width, height);

// function that saves the canvas
function SaveAsImage(){
   var canvas = document.getElementById("myCanvas");
   document.location.href = canvas.toDataURL("image/png");

Edited by Start4me: Inserted code snippet


A possible solution to convert the image to Base64 first, and then add it to your DOM. Afterward, you can save it as an image. You may need to apply the methods by combining/reading this link and this link.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.