Shifting an Image Within a Border
Determine which part of the image shows through when it's larger than the border containing it.
In essence, what you're doing is cropping the image by showing only a certain part of it within a div. The div is assumed to have a border, but it isn't required.
The image appears cropped to the shape of the border (or, if no border, where the border would be).
The technique is this:
-
Create a div of any dimension smaller than the image it will contain. Give it a border (or not).
-
Publish the image tag as the div's content.
-
Use JavaScript to scroll the image within the div to the point where the preferred part of the image shows through.
The Change Div Scroll Position article contains techniques for scrolling the content of a div to a desired position.
This article uses techniques explained in those two articles.
We'll use this image. Because of it's large dimensions, use the horizontal scrollbars to move the image and see it in its entirety.
To demonstrate their workability, the examples will show the middle part of the image.
This first example is the image in a square border, shifted so an area near the center of the image shows through.
Compare the visible portion with the full image further above. You'll see which part of the full image is being displayed.
Here's the source code. Explanation of the code follows.
<div id="example-1" style=" width:3in; height:3in; border:3px solid #999; overflow:hidden; "> <img src="//www.willmaster.com/images/lightfocus/WintersCastlebw.jpg" style="width:auto; height:auto; broder:none; outline:none;"> </div> <script type="text/javascript"> var divid1 = document.getElementById("example-1"); divid1.scrollTop = 120; divid1.scrollLeft = 160; </script>
Notice the several lines of JavaScript that follow the div.
The div's id value and the id value in the JavaScript are identical (colored blue in the source code). This is required so the JavaScript can move the image within the div.
The div's inline CSS (colored red) defines the div's width, height, border, and specifies overflow to be hidden.
The image tag is just a regular image tag, nothing special that affects the scrolling or div shape.
The JavaScript divid1.scrollTop and divid1.scrollLeft values (colored green) represent the number of pixels to scroll. But don't specify pixels, just the numbers.
And one more thing, the JavaScript variable name colored purple is different for each example. While testing, I found that in some browsers the variable's value would bleed from one example JavaScript to the next. Making each example variable different corrected that.
When the div's height is changed to height:2in; instead of height:3in; the result is a rectangle.
Here are the results of the height change.
Now you have the techniques at hand to crop images on a web page at the positions you want to crop them.
(This article first appeared in Possibilities ezine.)
Will Bontrager