简体   繁体   中英

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!

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 eg 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.

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?

Ie 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM