chacham15
chacham15

Reputation: 14281

How can I dynamically add text onto an image with HTML/Javascript/CSS?

I want to add text onto an image giving the text a transparent black background. Essentially, I want to achieve the effect described in the following link:

http://www.google.com/url?sa=t&source=web&cd=4&ved=0CD8QFjAD&url=http%3A%2F%2Fcss-tricks.com%2F3118-text-blocks-over-image%2F&rct=j&q=text%20on%20image&ei=IsmITsK4DYWc0AWj-4H9Dw&usg=AFQjCNHD2pL0MiEQObwT53pWzFq2gJoH6g&cad=rja

The problem is that I am dynamically generating these images and randomly placing them on the screen. Therefore, I cannot absolutely position the text (at least, not without knowing the height of the text in total). Is there another way to do this?

Thanks!

Upvotes: 0

Views: 9396

Answers (2)

Paul D. Waite
Paul D. Waite

Reputation: 98926

I am dynamically generating these images and randomly placing them on the screen.

Without seeing some of the code you have so far, it’s a bit difficult to help. If you’re dynamically generating the images, couldn’t you also dynamically generate the text along with it?

I.e. instead of generating:

<img style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;">

Could you generate:

<div class="image-with-text-over-it" style="position: absolute; top: RANDOMVALUE; left: RANDOMVALUE;">
    <img>
    <p>Text to be overlaid on image</p>
</div>

And then in your stylesheet, write some CSS that positions the text in every instance of this over the image in that instance:

.image-with-text-over-it p {
    position: absolute;
    bottom: 2em;
    left: 0;
    color: #fff;
    background: rba(0, 0, 0, 0.8);
}

Upvotes: 0

jancha
jancha

Reputation: 4977

you can position text absolutely. once images are loaded, even if randomly, jQuery's position() method will provide you will all the information you need.

obviously, you would like to to encapsulate images in containers e.g. or use and set image using div's background image. then you have all the freedom to put whatever text/effects you want in the container.

Upvotes: 1

Related Questions