7

Is it possible to show any part of image in img tag (with pixels) via JavaScript?

I would have a prepared big image (e.g. 32x320 pixels) and defined starting position (X,Y , e.g. 0,32) and width/height (e.g. 32,32), and would want the script to show second (32x32 pixel) part of main image.

Alper
  • 1,085
  • 3
  • 20
  • 39
  • Possible duplicate of [How can I display just a portion of an image in HTML/CSS?](https://stackoverflow.com/questions/57725/how-can-i-display-just-a-portion-of-an-image-in-html-css) –  Jul 07 '17 at 20:06
  • While referenced question is about html/css, this was for JavaScript. – Alper Jul 07 '17 at 20:14
  • are you aware that, since your question was implicitly about JavaScript DOM, and the DOM itself is just a programming backend for HTML/CSS, your question *was* about HTML/CSS itself? The accepted answer here point you to CSS for that very reason. You *can't* do JS DOM *without* taking account of HTML/CSS - even HTML5 canvas element mentioned in the other answer is just that - an HTML5 document element. –  Jul 07 '17 at 20:40

2 Answers2

10

You could use CSS properties for this and change them via JS. Set the image as a background for an element with your desired size and adjust its position with background-position so that the correct part of it is visible. Some people call it CSS sprites.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • +1 You don't even have to use a DIV. I use a transparent PNG and set its background-image, which works just as well for this purpose but gives me the option to use the artifact inline if I want to without having to deal with floats, etc. – Robusto Apr 04 '10 at 14:59
  • Yes, naturally this works with any element. Using an img element sounds somewhat dirty to me though, I'd probably use display: inline-block; if I wanted the element to flow with the text. – Matti Virkkunen Apr 04 '10 at 15:08
3

For the sake of giving you multiple options, you could always use an HTML5 canvas and redraw the image as necessary. You can find a nice tutorial about how to do this here : https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images The CSS sprite method would be preferable nonetheless as IE doesn't support canvas yet.

groovecoder
  • 1,551
  • 1
  • 17
  • 27
Gab Royer
  • 9,587
  • 8
  • 40
  • 58
  • you can even save the image you drew as a data url http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/ – Zig Mandel Jul 23 '14 at 03:24