0

I have a rectangle that is drawn using canvas. I know its startPosition(x: 731, y: 13) and endPosition(x: 768, y: 113). Can I get this element using JavaScript?

Here I got a JavaScript function document.elementFromPoint(x, y), but it doesn't serve my purpose, because it doesn't accept start and end position.

Can anybody give me idea of how can I retrieve my HTML rectangle element?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Arif
  • 6,094
  • 4
  • 49
  • 81
  • It is not an element. It's just part of the canvas image buffer. – D. Pardal Jul 14 '20 at 15:11
  • @D.Pardal Yes. you are right. – Arif Jul 14 '20 at 15:12
  • @D.Pardal I don't need to call `fillRect` because it's coming from a javascript library [resiumjs](https://github.com/darwin-education/resium#readme). But I can get startPosition and position on `onMouseEnter` – Arif Jul 14 '20 at 15:18

2 Answers2

1

You can't "get" elements from a canvas as you can with dom elements, as they aren't actually elements. The canvas just stores the pixel data rather than the individual objects that make up the image (eg lines and rectangles). Source.

If you're set on using the canvas, the typical method is to clear the parts being updated and re-draw anything being changed. You might store the canvas "elements" as a series of points which you reference when you redraw

dwb
  • 2,136
  • 13
  • 27
0

Can anybody give me idea of how can I retrieve my HTML rectangle element?

You can't, because it's not an element in the first place. Drawing in the canvas doesn't create any elements, it just changes the pixels in the canvas buffer.

If you want to draw shapes using JavaScript that you can later modify, I would suggest using the DOM with SVG.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37
  • Ok. Got it. In that case, can I get full `` element when I hover over the canvas? – Arif Jul 14 '20 at 15:23
  • You can, just use `document.getElementById()` or something like that, unless the `` is dynamically created via a library. – D. Pardal Jul 14 '20 at 15:25
  • I don't have any access on canvas, so I can't put any **id**. The canvas is drawn by [resium library like this](https://resium.darwineducation.com/examples/?path=/story/billboard--basic). It can be multiple canvas. – Arif Jul 14 '20 at 15:34
  • 1
    I get the feeling if you don't have direct access to the canvas, then you may be going about your problem in the wrong way. Are you *supposed* to be able to change it in that way? Are there other ways of achieving the same thing through this library? They may be better starting points. – dwb Jul 14 '20 at 17:13