nostradam
nostradam

Reputation: 83

Put text on image with Javascript

In my HTML, I have usual img element as follows:

<img src="images/main/car_48725.png">

I want to put text (to be more specific numbers) on this image, so that they can differentiate between various part of the image (it´s a car so one number should go on wheels, other on windows etc, depending on specific coordinates).

What is the way I can do this? I do not have this image inside a HTML5 canvas as I´m not using Canvas in my project.

Upvotes: 1

Views: 2218

Answers (3)

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9263

More efficient using MAP element HTML; based on this example from w3schools With the help of imagemaps you can do that more fast and simple !

function clicked(obj){
  console.log(obj.title)
}
<p>Click on the wheels, the door, or the glasses  of the car to show title of it!</p>
<img src="https://th.bing.com/th/id/OIP.O_8ACkiHyjX-JtYCZnCKDgHaEZ?pid=ImgDet&rs=1" alt="Kevin's_Car" usemap="#image-map">

<map name="image-map">
    <area onclick="clicked(this)" alt="front wheel" title="front wheel" href="#" coords="239,230,33" shape="circle">
    <area onclick="clicked(this)" alt="back wheel" title="back wheel" href="#" coords="411,169,30" shape="circle">
    <area onclick="clicked(this)" alt="door" title="door" href="#" coords="306,134,380,188" shape="rect">
    <area onclick="clicked(this)" alt="glass" title="glass" href="#" coords="244,88,280,92,313,98,291,138,215,122,177,107,213,82" shape="poly">
</map>

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075735

You can position elements with transparent backgrounds on top of the image. Here's just one way:

.overlap {
    position: relative;
}
.overlap img,
.overlap .text {
    position: absolute;
}
.overlap .text {
    color: blue;
    font-family: sans-serif;
}
.x {
    top: 0;
    left: 0;
}
.y {
    top: 10px;
    left: 10px
}
.z {
    top: 20px;
    left: 20px;
}
<div class="overlap">
    <img src="https://via.placeholder.com/150">
    <div class="text x">x</div>
    <div class="text y">y</div>
    <div class="text z">z</div>
</div>

The container div is position: relative so that it's an offset parent for the elements within it. Then you can position the elements within it using left and top (in CSS, or by assigning to someElement.style.left and someElement.style.top [remember the px suffix]).

Upvotes: 1

Arturo Ortueta
Arturo Ortueta

Reputation: 11

You can put the <img src="images/main/car_48725.png"> inside a <div> then create a label as child of the <div> and play with the position of the label and that´s it.

Upvotes: 0

Related Questions