26

I want to have an image which is uploaded from my database and on top of it the exact same size in the same position is a HTML5 canvas.

Most of the solutions I have found I have been using JQuery/JavaScript, however I want a similar solution if possible just using CSS3 as the images are being outputted from a database and there can be more than one image on the page and each image will have a canvas.

How can I achieve this?

0

2 Answers 2

26

Yes.

You can do this entirely in CSS, but you will have to add some specific HTML plumbing for each image.

If you ever get tired of the extra plumbing, javascript could do most of the plumbing for you.

Here is a Fiddle of the CSS-only version:

http://jsfiddle.net/m1erickson/g3sTL/

The HTML:

<div class="outsideWrapper">
    <div class="insideWrapper">
        <img src="house-icon.jpg" class="coveredImage">
        <canvas class="coveringCanvas"></canvas>
    </div>
</div>

Of course, in your version, you would replace the image src with your dynamic database call to fetch the image.

The CSS:

.outsideWrapper{ 
    width:256px; height:256px; 
    margin:20px 60px; 
    border:1px solid blue;}
.insideWrapper{ 
    width:100%; height:100%; 
    position:relative;}
.coveredImage{ 
    width:100%; height:100%; 
    position:absolute; top:0px; left:0px;
}
.coveringCanvas{ 
    width:100%; height:100%; 
    position:absolute; top:0px; left:0px;
    background-color: rgba(255,0,0,.1);
}
3
  • 2
    Is there a way to make this work for a list of images without knowing the image sizes in advance? Removing the width/height from the outer wrapper makes all images and canvases in all these double div wrappers render in one spot. Commented Sep 20, 2017 at 23:13
  • Figured it out. I'm using Flask so python can read the image dimensions and Jinja can set an inline style for the outsideWrapper divs equal to the dimensions. Commented Sep 21, 2017 at 20:02
  • 1
    Important side note: the css width and height are not the same as <canvas width="100" height="100>. If you are going to use the canvas for drawing it won't work as expected. More details stackoverflow.com/questions/15639726 and stackoverflow.com/questions/2588181
    – yeya
    Commented Oct 17, 2018 at 9:27
3

Possible duplicate.

Depending on how many images are in the database, you could have a separate canvas id for each with the name of the image file (e.g. canvas #foo { background:url(foo.jpg) }). I would load this in a separate stylesheet. :)

It would probably be easier to maintain a Javascript solution though if your database is dynamic. A few lines of javascript would be sufficient, instead of constantly updating a stylesheet with new names. Less error typo prone as well.

Not the answer you're looking for? Browse other questions tagged or ask your own question.