Display scalable images

  • Tutorial
The traditional work of HTML image pages is to open images instead of these pages. It's time to stop this inconvenience on a single site. Links are good, but convenient browsing is better.

What is convenient viewing? Example " light boxes " of different shows that it is better to open psevdookno view within the document without deleting the document. But when reading articles, this approach is not very convenient. We do not see the context of the document. It turns out that either a picture or a document is visible. It is better if the picture does not cover the text, as organized, for example, in the Dollchan Extension Tools script (suggested here), where viewing pictures takes up a small part of the overall functionality of viewing "imageboards" - about the same text-picture streams of articles. We will do the image management controls, adding something of our own.

Briefly: what happened as a result


Script for viewing images on the site pages:
  • without reloading the page and not in a new tab - in the center of the page in a thin frame;
  • the initial scale is 100% or limited by the window;
  • with scaling by mouse wheel;
  • without shading the surrounding document;
  • with drag and drop on the window space;
  • Support for Firefox / Chrome / Opera.
Implementation - user script for 1 site.
Pictures that look:
  • represented by a link to the full image;
  • forcedly scaled down (do not fit in a column);
  • are placed at a scale of 100%, but can be viewed with an increase (initially 200% or within the window);
  • have a size of more than 22 pixels.
Additionally:
  • You can follow the link in the figure to a new tab if you hold Ctrl, or click the middle mouse button;
  • Search in 1 out of 5 search engines for pictures - Google, Tineye, Yandex and a couple of others (hold Shift on click to see this menu).

Settings (change in the settings menu):
  • the script is enabled by default;
  • link preloading of images is disabled (preventing excessive traffic);
  • viewing of unmarried pictures in an initial scale of 200% is enabled by default.


Next will be sequentially considered: ideas, rules of interface behavior, implementation details, algorithm, examples. There will be no review of the code - it is in the implementation, written in pure JS and performs its role, nothing else is required. It can be used both practically, in a finished implementation (we take and look at the pictures on the site), and for installation on another site (LGPL v3). And now - in all the details ...

Reasons (search for a better life)


There are several instances of the appearance of tags with images in HTML, when an improved viewing approach is desired. Consider the examples and come up with the rules of how best to deal with viewing pictures.

1) Link. On the page there is a link leading to a static image with the extension jpg, jpeg, gif, png.
Example : a link to a picture (randomly taken types of cursor patterns).
Example 2 : link to the big picture: infographics about Android (300 K) from the article “Android in numbers” .
Solution : display the image (making it download) in a reduced size next to the link. Click to view.

If we move on to viewing the picture in full size, then the picture appears in the center of the window, occupying the maximum space in width or height. Using the mouse wheel, we scale it, and by dragging - we move it. By clicking on the source image or on the one being viewed, close the view. By clicking on another preview - go to view another picture.

2) Mini preview. The page has a thumbnail with a link revealing a (usually) enlarged original.
An example :

Solution : display the original in a hidden block to find out its size. By clicking on the link - view.

It should be emphasized that in cases 1 and 2 we do the loading of images by links in automatic mode - all links on the page. If there is no unlimited Internet, you need to remember that these methods of viewing will lead to excessive traffic, if the author of the texts specially hid multi-megabyte images under the links. So, you need to be able to disable and enable these modes by setting " load links ".

3) Width limit. On the page, due to the beautiful design, the pictures are compressed to the width of the text column. I want to see the full width, but for this you need to expand the browser window.
Example : wide picture (204 K)

Solution : mark the picture with a special cursor, for example, “move” . So, by clicking on it, we’ll go to the maximum view.

4) what to do if we see a picture that fits perfectly in the text?
Example : small picture:

Solution : there are 2 options: either do nothing (the “ watch double-sized pictures ” setting is disabled), or show it in a 2x enlarged view and mark it with a special cursor (for example, “ne-resize” - or ).
(Types of browser system cursors in Windows , in other systems , how to change the mouse cursor .)

Cases 3 and 4 do not imply additional loading of images, but only improve viewing. Therefore, they can not be turned off by the site’s user settings. They intercept clicks on links, so if nothing is foreseen, there will remain an inconvenient way to click on the link “Right-click - View in a new tab”. Therefore, in the script, we will disable the viewing functions if the Ctrl key is held down.

More detailed rule 2


(2.a) Several pictures under the link to the picture. There is a link to a static image, determined by the file extension, and inside it there are various, possibly complex HTML content.
Solution :
*) if there are no image tags inside the link, put a small copy of the downloaded image on top (no more than 200 by 200 pixels).
*) If there is only 1 picture with tags around, and possibly with text, then we consider that this is a classic preview in the form of a small picture with a link to a large one.
*) If the link has a more complex internal structure (more than 1 IMG tag), then a separate preview is built for the link and separately - the inside of the link, viewing its pictures. (This case is rare, but it needs to be taken into account in the algorithm. They can, for example, make a compound word from pictures and put a link.)
If you get a large picture - more than 50% of the window width, put the cursor to indicate viewing at 100%. We view it with an increase of 200% if the image width is less than 50% of the window width. Clicking on the image opens the link.

Example : a difficult case: cursors: on the outside - a link to a table with cursors, and inside small pictures:
e-resize:, nw-resize:, crosshair:

	e-resize: ,
	nw-resize: ,
	crosshair: 


Algorithm


From the rules follows an algorithm. First, we go over the HTML (or DOM) area, look for links to images. Having found, we check the number of IMG tags inside. If 0 - viewing a link by clicking on a separately generated image. If there is only one, we arrange viewing the link by clicking on the IMG, and the attribute class “do not add your own view” (_noAddOwnView) is added to the IMG class. If there is more than one IMG tag - viewing the link separately, as in the case of 0 IMG tags, and each IMG is also viewed separately (but they will be prepared for viewing in the 2nd pass).

The second pass of the elements is looking for an IMG. All that do not have _noAddOwnView are drawn up for viewing (an invisible DIV appears in front of them with an invisible picture attached - an IMG take to measure its actual size). The same view is added to all _noAddOwnView, but the picture is replaced by the address of the parent link (the link can be a parent not of the first level, but older). All preview images created on the 1st pass are not affected (are eliminated by the _noAddOwnView class).

Special Feature Enhancements


Service pictures and the rest inside the links are framed by a link. But clicks on pictures are intercepted by preventDefault () , that is, links do not work. It would be interesting to have the usual behavior of the link if we want to view the picture in a new tab by pressing the Ctrl key before clicking the button (as is usual in Firefox and Chrome to open the link in a new tab). Therefore, by pressing Ctrl all view actions are canceled so that the link opens in a new tab.

To get a number of features, holding the Shift button displays the context menu for the pictures. It will contain all the desired operations that did not fit on a mouse click. For example, viewing a preview imageenlarged view (what was hidden when there were links around, although it is hardly necessary to view thumbnails), search through image search engines (5 links). If desired, other features are added to the menu.

Let also small pictures (less than 23x23 pixels), sometimes used as official ones, such as these: are not provided with a preview.

Implementation


All these viewing options are possible with the HabrAjax script version 0.901 (dated January 21, 2013) on the Habr's pages.

Thus, users of the user script freed themselves from the shackles of viewing images on a scale of 1 to 1, or in the reduced size, which is so rich in collective blogs. You can even move the picture to another part of the page, comments, by scrolling the page scroll in the picture view mode.

And that's not it. If the user has enabled the " Force cut", картинки из аннотаций в ленте уменьшаются (было сделано довольно давно, месяцев 8 назад). Чтобы увидеть полные картинки, требовалось просмотреть статью. Теперь, по клику на картинке, также смотрим её в полном размере и с перемещением по окну. Все картинки принудительного ката тоже получили освобождение.

Надо снова предупредить: настройка "подгружать ссылки-картинки" увеличивает трафик. Включать её имеет смысл на безлимитных тарифных планах. Чтобы скрипт не был ответственным за неосознанный расход трафика, добавлено подтверждение пользователем этого предупреждения: 'Включена настройка «Подгрузка рисунков», но не подтверждена. Согласны ли Вы с увеличением трафика за счёт подгрузки рисунков?'. Нужно один раз согласиться, что будет запомнено в настройках.

To look at examples of this holiday of life, after installing the script, visit such pages. (We ’ll select interesting articles from the recent past.) And to see everything, turn on the “ load image links ” setting (click on the script logo on the right or “HAjax” in the user settings menu, and then select the checkbox in the list - Save - reload the page )

* " Curiosity at the bottom " - Mars photos for the most part have a width of 1100px - on narrow windows they are pressed with styles across the width of the column. Click - and all conventions are removed. There are large photos in the comments, which are also available for viewing to scale.

The percentage of scale is shown in the text tooltip, and when it falls within the limits of 88-113% it is set to 100% (or 200%, depending on the type of view).

* " Amazing Mars " - some beautiful large and 2 very large (by links to them) pictures.

* " When every day as DDOS. The largest Chinese sites " - there, between the first and second pictures under the numbers "83%" there appears an infographic - a large JPG of 4000 pixels high, occupying 200px in a reduced form.load image links "- it is not there, but the link is used for normal viewing.

* habrahabr.ru/feed/new or any other feed with the" Forced cut " setting . Small images are viewed at a size of 100%, and if they are less than 200 by 120 - then in the amount of 200%.

* " Javascript and canvas in the game" Life "by John Conway " - the first large picture under a preview of 1300 pixels is perfectly visible inside the page, and the remaining small ones are viewed in the "x2" mode (200% of their size ).

*) and, for example, the article " Catalan numbers " with a number of pictures of different sizes and degrees of transparency.

Setting "If enabled viewing of pictures " (in the window in the center ), then all the pictures on the page no longer replace the page, as is customary on the site, and they don’t even just open in a new window, as was done not so long ago (4 months ago) in HabrAjax, but open in as a maximum-sized image inscribed in the window frame and centered relative to it. If it is smaller than the window, the picture is centered. At the same time, shading does not interfere with reading the page - there is no shading, in contrast to the lightbox-like scripts.

Example 1 : a screenshot of viewing a large screenshot from an article about the Habr viewer on iOS . The cursor on the preview image is “ne-resize”, and the preview indicates the size of the full image. Example 2

: A screenshot of a forced-thumbnail view showing that the zoom is displayed in a tooltip.

You can move the picture to read the page, and use the mouse wheel to change its scale. Click to close. By clicking on the original image - too.

In addition to the functionality available in Dollchan , we expand the amenities. When you hold Ctrl while clicking on the original image, it opens in a new tab. When Shift - opens the search menu for image search engines. Another group of amenities is opened for working with forcedly reduced images from the “forced kat”. If it is reduced, clicking on it shows its original size in the image viewing format.

Not neglected viewing pictures from the infographics of comment branches- recent experimental visualization of the comment tree. Near the branches are marked icons of pictures in the form of small orange-yellow rectangles. By hovering over the icon you can see the name of the picture and small previews (if you " load links-pictures "), and by clicking - you can see the full picture. Thus, without scrolling through the viewing window, you can quickly evaluate which pictures are sketched into a long comment tree, sometimes a dozen or more browser windows long.

Example 3 : an article in which there are many pictures in the comments: " LED strip as room lighting". Even that one picture, which is presented in the form of a link, looks like a" orange lit "rectangle in an even matrix of links. Those images that couldn’t load (the picture in the bottom row of someone from the dropbox) are not previewed. Finally, fixed and a rather painful place of the existing layout of pictures: they cannot be larger than the width of the strip of viewing the article or the tape. If the script detects that the picture is forcibly reduced by the layout, it applies the same viewing methods to it. Now in narrow windows but to see all the images, without extending the window and opening them in a new tab. Examples of the beginning of the article is perfectly illustrated by the results, if you set HabrAjax and pereotkroete this page.




Codes


All codes of this functionality, apart from the procedures used, are written in the HabrAjax user script under the function names addFullImg, handlImgViews in pure JS and occupy about 200 lines.

The basic algorithms were taken from the Dollchan script, but their application was strongly transformed, turning from 6-7 basic functions into 2, and also used our own utilities (library functions) instead of the original ones. This helped to better structure the code, although there was no task of completely processing the original one - some “utilities” were taken in their original form ( $ pd, $ offset ).

They can be used to build your own image viewer (LGPL v3). But there was also no such task (to make a plug-in for connecting image viewing), so there is no (yet) separately laid out code on the Github. However, by copying image viewing functions and setting tags for your own website, this is doable, similar to copying from Dollchan. Feature - these scripts do not support IE8 and lower. For support, you need to make cross-browser additions, for example, use the jQuery $ () function for selectors .

Only registered users can participate in the survey. Please come in.

Did you like the example screenshots?

  • 26.6% Yes, quite in the spirit of Habr. 24
  • 27.7% No, kittens would be better: http://fishki.net/comment.php?id=15487 25
  • 3.3% No, better than dolls: http://onua.com.ua/1277-kukly-iz-japonskikh-anime-multikov-57-foto.html 3
  • 14.4% only text, only hardcore! thirteen
  • 27.7% topic *** not disclosed: http://www.rulez-t.info/girls/11962-risovanaya-fyentezi-yerotika.html 25

Also popular now: