How to best overlay a canvas on an image?

2019-04-12 02:08发布

问题:

I would like to place a canvas on top of an image that I have on a page. The canvas will be the exact dimensions of the image.

However, the following conditions must be met:

  • The canvas must remain exactly on top of the image at all times. Therefore, using absolute positioning will not work because if content is inserted above the image, it will move the image down without moving the canvas.
  • The image may be resized from its original size. Therefore, replacing the image with the canvas and setting its background to the image will not work.

What options do I have?

回答1:

You should be able to use position:relative instead of absolute for your first requirement.

For the second I'm guessing you could put both the image and the canvas inside of a span. The canvas would have a width/height of 100% and would be resized as the image resizes because the size of the div would change to fit the image.

EDIT: actually I'm not sure position:relative would work. But I believe if you use position:absolute and the parent element has position:relative, than the absolute positions will be relative to the parent.