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="" 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.

Recommended Answers

All 4 Replies

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.

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.

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=''>
// 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");

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.