DEV Community


Discussion on: How to make Dynamic Text Overlays on Images

sarthology profile image
Sarthak Sharma Author

I think it can be. But it might take a lot of werid calculations to do something like that. But Iā€™m up for the challenge. šŸ˜Ž

Thread Thread
kenbellows profile image
Ken Bellows

It's not too bad as long as you know (or can get) three things:

  • the size the image will be when rendered
  • the pixel position of the text relative to the top-left corner of the image
  • the approximate height and width of the text when rendered

That last bit is the hard part, especially if there's any line breaks involved. But after you have those, it's basically this:

const start = { x: img left + text rel left, y: img top + text rel top }
const end = { x: img left + text rel left + text width, y: img top + text rel top + text height }
for (const x = start.x; x < end.x; x++) {
  for (const y = start.y; y < end.y; y++) {
    const p = (canvas.width * y + x) * 4
    const [r, g, b] =[], p, p+3)
    // fancy logic of choice