Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting part of an image with JavaScript

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.

like image 771
Alper Avatar asked Apr 04 '10 14:04

Alper


People also ask

What is image () in JavaScript?

Image() The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document. createElement('img') .

Can JavaScript display images?

Create “show()” function in JavaScript which can get the image and add the image source link to the src attribute.

How do you reference an image in JavaScript?

In JavaScript, get a reference to the image tag using the querySelector() method. Then, assign an image URL to the src attribute of the image element.

How do I make an image occupy a whole div?

To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.


2 Answers

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.

like image 97
Matti Virkkunen Avatar answered Oct 07 '22 16:10

Matti Virkkunen


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.

like image 38
Gab Royer Avatar answered Oct 07 '22 16:10

Gab Royer