Are there any documents/tutorials on how to clip or cut a large image so that the user only sees a small portion of this image? Let's say the source image is 10 frames of animation, stacked end-on-end so that it's really wide. What could I do with Javascript to only display 1 arbitrary frame of animation at a time?
I've looked into this "CSS Spriting" technique but I don't think I can use that here. The source image is produced dynamically from the server; I won't know the total length, or the size of each frame, until it comes back from the server. I'm hoping that I can do something like:
var image = getElementByID('some-id');
image.src = pathToReallyLongImage;
// Any way to do this?!
image.width = cellWidth;
image.offset = cellWidth * imageNumber;
This can be done by enclosing your image in a "viewport" div. Set a width and height on the div (according to your needs), then set position: relative and overflow: hidden on it. Absolutely position your image inside of it and change the position to change which portions are displayed.
To display a 30x40 section of an image starting at (10,20):
<style type="text/css">
div.viewport {
overflow: hidden;
position: relative;
}
img.clipped {
display: block;
position: absolute;
}
</style>
<script type="text/javascript">
function setViewport(img, x, y, width, height) {
img.style.left = "-" + x + "px";
img.style.top = "-" + y + "px";
if (width !== undefined) {
img.parentNode.style.width = width + "px";
img.parentNode.style.height = height + "px";
}
}
setViewport(document.getElementsByTagName("img")[0], 10, 20, 30, 40);
</script>
<div class="viewport">
<img class="clipped" src="/images/clipped.png" alt="Clipped image"/>
</div>
The common CSS properties are associated with classes so that you can have multiple viewports / clipped images on your page. The setViewport(…) function can be called at any time to change what part of the image is displayed.
In answer to :
Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML element combined with a bit of server-side scripting.
...
< ? (open php)
$large_image = 'path/to/large_image';
$full_w = imagesx($large_image);
$full_h = imagesy($large_image);
(close php) ? >
This can be done in Javascript, just google a bit :
var newimage = new Image();
newimage.src = document.getElementById('background').src;
var height = newimage.height;
var width = newimage.width;
This generates a new image from an existing one and captures this way in java script the original height and width properties of the original image (not the one id'ed as background.
In answer to :
The width/height properties of the document's image object are read only. If you could change them, however, you would only squish the frames, not cut the frames up like you desire. The kind of image manipulation you want can not be done with client-side javascript. I suggest cutting the images up on the server, or overlay a div on the image to hide the parts you do not wish to display.
...
var newimage = new Image();
newimage.src = document.getElementById('background').src;
var height = newimage.height;
var width = newimage.width;
newimage.style.height = '200px';
newimage.style.width = '200px';
newimage.height = '200px';
newimage.width = '200px';
and if wanted :
newimage.setAttribute('height','200px');
The doubled newimage.style.height and newimage.height is needed in certain circumstances in order to make sure that a IE will understand in time that the image is resized (you are going to render the thing immediately after, and the internal IE processing is too slow for that.)
Thanks for the above script I altered and implemented on http://morethanvoice.net/m1/reader13.php (right click menu... mouseover zoom lent) correct even in IE , but as you will notice the on mousemove image processing is too fast for the old styled IE, renders the position but only once the image. In any case any good idea is welcome.
Thanks to all for your attention, hope that the above codes can help someone...
Claudio Klemp
http://morethanvoice.net/m1/reader13.php
CSS also defines a style for clipping. See the clip property in the CSS specs.
The width/height properties of the document's image object are read only. If you could change them, however, you would only squish the frames, not cut the frames up like you desire. The kind of image manipulation you want can not be done with client-side javascript. I suggest cutting the images up on the server, or overlay a div on the image to hide the parts you do not wish to display.
What spriting does is essentially position a absolutely-positioned DIV inside another DIV that has overflow:hidden. You can do the same, all you need to do is resize the outer DIV depending on the size of each frame of the larger image. You can do that in code easily.
You can just set the inner DIV's style:
left: (your x-position = 0 or a negative integer * frame width)px
Most JavaScript Frameworks make this quite easy.
Alas, JavaScript simply isn't capable of extracting the properties of the image you'd require to do something like this. However, there may be salvation in the form of the HTML <canvas> element combined with a bit of server-side scripting.
PHP code to go about extracting the width and height of the really large image:
<?php
$large_image = 'path/to/large_image';
$full_w = imagesx($large_image);
$full_h = imagesy($large_image);
?>
From here, you'd then load the image into a <canvas> element, an example of which is documented here. Now, my theory was that you may be able to extract pixel data from a <canvas> element; assuming that you can, you would simply make sure to have some form of definite divider between the frames of the large image and then search for it within the canvas. Let's say you found the divider 110 pixels from the left of the image; you would then know that each "frame" was 110 pixels wide, and you've already got the full width stored in a PHP variable, so deciphering how much image you're working with would be a breeze.
The only speculative aspect to this method is whether or not JavaScript is capable of extracting color data from a specified location within an image loaded into a <canvas> element; if this is possible, then what you're trying to accomplish is entirely feasible.
I suppose you want to take a thumbnail for your image. You can use ImageThumbnail.js that created from prototype library in this way:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="ImageThumbnail.js"></script>
<input type="file" id="photo">
<img src="empty.gif" id="thumbnail" width="80" height="0">
<script type="text/javascript">
<!--
new Image.Thumbnail('thumbnail', 'photo');
//-->
</script>
for more information
try use haxcv library haxcv js by simple functions
go to https://docs.haxcv.org/Methods/cutImage to read more about his library
var Pixels = _("img").cutImage (x , y , width , height );
_("img").src (Pixels.src);
// return cut image
but try to include library first
Related
Note that I'm not asking how to make a div the size of the "window" or "viewport" for which there are plenty of existing questions.
I have a web page of some height and width, and I'd like to add an empty, top-level div (i.e., not one containing the rest of the page) with a size exactly equal to the page's height and width. In practice, I also want it to be at least the size of the viewport.
I know I can do a one-time calculation of the height and width in JavaScript:
var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
But this value can change based on images loading, or AJAX, or whatever other dynamic stuff is going on in the page. I'd like some way of locking the size of the div at the full page size so it resizes dynamically and on-demand.
I have tried something like the following:
function resetFakeBg() {
// Need to reset the fake background to notice if the page shrank.
fakeBg.style.height = 0;
fakeBg.style.width = 0;
// Get the full page size.
var pageHeight = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var pageWidth = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
// Reset the fake background to the full page size.
fakeBg.style.height = pageHeight + 'px';
fakeBg.style.width = pageWidth + 'px';
}
// Create the fake background element.
fakeBg = setFakeBgStyle(document.createElement('div'));
document.body.appendChild(fakeBg);
// Keep resizing the fake background every second.
size_checker_interval = setInterval(resetFakeBg, 1000);
Limitations
This is for a Chrome extension, and I'd like to limit my modification of the page to adding this single div. This means that adding CSS to modify the height and width of the html and/or body tags is undesirable because it might have side-effects on the way the rest of the page is rendered.
In addition, I do not want to wrap the existing page in the div because that has the potential to break some websites. Imagine, for example, a site styled with the CSS selector body > div. I'd like my extension to break as few websites as possible.
WHY OH WHY WOULD I NEED TO DO THIS?
Because some people like to hold their answers hostage until they're satisfied that I have a Really Good Reason™ for wanting to do this:
This is for an accessibility-focused Chrome extension that applies a CSS filter across an entire page. Recent versions of Chrome (>= 45) do not apply CSS filters to backgrounds specified on the <html> or <body> tag. As a result, I have chosen to work around this limitation by copying the page's background onto a div with a very negative z-index value, so that it can be affected by the page-wide CSS filter. For this strategy to work, the div needs to exactly imitate the way the page background would appear to a user—by being the exact size of the document (and no larger) and at least filling the viewport.
setInterval() is your best friend in cases like this where you want the .height() and .width() of an element to be asynchronously specified all the time to something that can be dynamicly altered by user input and DOM tree changes. It is what I dub as a "page sniffer", and arguably, works better than $(document).ready if you are working in multiple languages (PHP, XML, JavaScript).
Working Example
You should get away with setting the width and height in the window resize function, you might wanna add it in a load function as well, when all data/images are loaded.
just add width=100%
e.g;-
Hello World
I think you must do it like this:
...
<body>
<script>
function height()
{var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);}
function width()
{var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);}
</script>
<div height="height()" width="width()">
</div>
</body>
...
I am a skilled database / application programmer for the PC. I am also an ignorant html / javascript / web programmer.
I am creating some documentation about some .Net assemblies for our intranet. Ideally I would like to display an image full size if the browser window can fit it. If not then I would like to reduce it and toggle between a small version and full size version by a click. It is a dependency chart and can be different sizes for different pages. I would prefer a single function to handle this but being it is for our use none of the requirements I mentioned is set in stone. I would like to make it work well but nothing is mandatory.
I read a lot of stuff but couldn't find anything that matched what I wanted. First I tried this (after a few iterations):
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width=this.naturalWidth;this.height=this.naturalHeight;' ondblclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width="100%";'>
It has problems. First off it enlarges a small image and it looks funny. Second I would have to put the code in every page. Third it requires a double click to restore it. I was going to live with those short commings but the double click fails. I can't figure out how to restore it.
So I tried to get fancy. I couldn't figure out how to get past problem 1, but solved 2 and 3 by creating a function in a separate file. Then I ran into what appeared to be the same problem. This was my second attempt:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.width='100%';
ImageToggle.FullSize = false;
}
else
{
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 0
}
And in my page:
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='ImageToggle(this)'>
Can what I want be done? It doesn't sound impossible. If it is a large amount of effort would be required then alternate suggestions are acceptable.
You're probably interested in the max-width: 100% CSS property, rather than a flat-out width:100%. If you have a tiny image, it'll stay tiny. If you have a huge image, it gets resized to the width of the containing element.
For example: http://jsbin.com/kabepo/1/edit uses a small and a huge image, both with max-width:100%. As you can see, the small image is untouched, the huge image is resized to something sensible.
I would recommend that you set a the max-width: 100% CSS property for the image.
This will prevent the image's width from expanding to be greater than the container's width.
You can also do the same with max-height: 100% if you are having problems with the image overflowing vertically.
Please see this JSFiddle for an example.
(Note: If you set both a width and a height attribute on the <img> tag directly or in your CSS file your image will not be scaled proportionally.)
Does it have to be a toggle or would a mouseover work for you as well?
<style>
.FullSize { width:100px; height:auto; }
.FullSize:hover { width:90%; height:auto; }
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
Note: when image is made larger IN the page - the surrounding content will be displaced around it - depending on how you have set up the layout.
Also if you have any body margins or table or div paddings, using image width at 100% will make the page scroll. To check just change 90% to 100% and work your way up / down.
You could also force the image to be a specific size until the browser gets made smaller by the user / has a smaller resolution.
<style>
.FullSize {width:1000px;max-width:100%;height:auto;}
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
A tip: the image used must be the largest one. So minimum width of lets say 1200 pixels wide (if that is the forced image size you use). That way regardless of size it is it will remain clearer than a small image becoming a large. Since it's an intranet, file size shouldn't be an issue.
Thanks all for your help. Rob and Mike both pointed me to an excellent solution. I now have my page load with an image that fits the browser window, resizes with the browser and if the user is interested they can expand the image and scrollbars appear if necessary. I got this to work in a function so minimal code is needed for each page.
To load the image:
<p style="overflow:auto;">
<img src='Dependancy Charts/RotairAORFQ.png' width="100%" onclick='ImageToggle(this)'>
</p>
And the function:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.style="max-width: 100%";
ImageToggle.FullSize = false;
}
else
{
Image.style="max-width: none";
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 1
}
if you want to get current browser window size and if you want to do it on a click event so try this in jquery or javascript:
<script>
$("#myButton").click(function(){
var x = window.innerHeight; // put current window size in x (ie. 400)
});
</script>
I need to add a Transparent image on top of all images on a page. The goal is if a user were to do a simple right click and save of an image, they would save the transparent image.
I do realize this is not a guaranteed method and that none exist to prevent image theft but simply a measure that a client wants added to prevent your average non tech person from saving images.
Using JavaScript I would like to find all images or all images within a certain Div.
Apply a new image overlay on top of these images that will have the same width and height of the image they are covering
I am not sure how to do this with JavaScript and was hoping someone would have a quick fix or example. I was unable to find anything so far on Google or SO. Appreciate any help
I have this JS which gets all images on a page so far...
// Get all images on a Page
function checkimages() {
var images = document.images;
for (var i=0; i<images.length; i++){
var img =images[i].src;
// Add new transparent image on top of this image
alert(img);
}
}
I would advise you to work with jQuery (or similar library) to keep things easier. I would even write a small jquery extension to make it easy to recycle the code, and apply it on any div (or other wrapper), wich child images you want to be overlayed.
My code would look something like this:
// jquery plugin to create overlays
// src is the url of the overlay image
// apply to any container that contains images to be overlayed
$.fn.overlayImages = function(src) {
// loop trough the images
$(this).find('img').each(function() {
// cache some variables
var $img = $(this);
var $parent = $img.parent();
// make the parent relative, if not yet absolute or fixed, for easy positioning
if ($parent.css('position') !== 'fixed' && $parent.css('position') !== 'absolute') {
$parent.css('position', 'relative');
}
// get the position of the image
var position = $img.position();
// clone the image
var $overlay = $img.clone();
// set the styling, based on the img, for exact positioning
$overlay.css({
top: position.top,
left: position.left,
position: 'absolute',
width: $img.width(),
height: $img.height()
});
// change the src attribute for the overlay
$overlay.attr('src', src);
// insert the overlay to the DOM
$overlay.insertAfter($img);
});
}
// when the DOM is loaded (not just ready, the images need to be there to copy their position and size)
$(window).load(function() {
// apply the overlay plugin to the wrapper of the images
$('#replace-images').overlayImages("http://www.riptideinnovations.com/images/watermark.png");
});
I added the step by step explanation inside the code as comments, but do feel free to ask if you want any further explanation.
I set up a small fiddle to demonstrate: http://jsfiddle.net/pP96f/6/
I don't know if this would help, but you could make your images all div's with backgrounds like this:
<div style="background-image: url('<your_image>');"></div>
I'm trying to show an image (of arbitrary width/height) in full screen when the screen (also of arbitrary width/height). I'm using HTML/CSS/JS. I want the image to always take up the full screen. If the image is a lower aspect ratio than the screen then I should clip the top and bottom. If the image is a higher aspect ratio than the screen then I should clip the left and right. I never want to see black around the edges.
I can do it using background-image (and background-position, etc.) but I'm having an issue with that (the image flashes as I update it). So I'd like to use an tag. Does anyone know how I'd do that?
I think the question is nice and clear and obviously the OP doesn't have any code... that's why he's asking the question.
I've run into that exact issue before. I don't think there's a way to do it using HTML/CSS if you want the image to end up larger than the containing element with the excess clipped unless you can put the image in the background. If you need to use the tag as you state, then a good solution is to do this imperatively. Here's what I did.
function setImagePosition() {
var img = q(".viewCamera #viewport img");
if (outerWidth/outerHeight > img.naturalWidth/img.naturalHeight) {
img.style.width = format("{0}px", outerWidth);
img.style.height = "";
img.style.top = format("{0}px", (outerHeight - img.clientHeight) / 2);
img.style.left = "0px";
} else {
img.style.width = "";
img.style.height = format("{0}px", outerHeight);
img.style.top = "0px";
img.style.left = format("{0}px", (outerWidth - img.clientWidth) / 2);
}
}
Let me explain...
The outerWidth/outerHeight results in the aspect ratio of the window. The img.naturalWidth/img.naturalHeight is the aspect ratio of the image. If the first is greater then we need to set the width of the image to the width of the window and calculate the top value to center the image vertically. If the second is greater then we need to set the height of the image and then use the left to center the image horizontally.
Hope that helps! You can find a bunch of Windows 8 HTML/JS related help in my codeSHOW project at codeshow.codeplex.com and in the Windows Store at aka.ms/codeshowapp.
If you are using jQuery, have a look at these:
http://vegas.jaysalvat.com/
or more lightweight:
http://srobbin.com/jquery-plugins/backstretch/
if you want it to stretch use background-size, or if it has to be a tag, use max-width:100%; in order to center use display:block; and margin:0 auto;
Im not quite sure what youre after though...
How do you update the image so it flashes? When does it occure? It sounds like a job for background-position:center.
I've got couple of lines of JavaScript using jQuery to resize images to thumbnails.
var thumb = $(this);
thumb.load(function() {
var ratio = thumb.height() / config.maxHeight;
var newWidth = Math.ceil(thumb.width() / ratio);
thumb.height(config.maxHeight);
// this line matters
thumb.width(newWidth);
});
Fotunately this works fine. But if I replace the last line with:
thumb.width(Math.ceil(thumb.width() / ratio));
It changes width of images that hasn't got explicitly defined dimensions badly (too narrow). To me, it seems like totally equivalent ways - via a variable or directly - but obviously they're not.
I tried casting the ceil() result to a Number or Integer and it behaved opposite way - images with undefined dimension were OK but the rest was too wide (width of original image).
Although I the first solution works I guess there's something fundamental I'm missing. So I want to avoid it in the future.
Thank you!
I would guess that the <img> element you are manipulating does not have declared height or width attributes. If that is the case, then the issue is how browsers intelligently resize images given only one constraint.
If you have an image that is 1000px wide, and 1000px tall, and you write an IMG tag like this:
<img src="big_image.gif" width="10" />
Modern browsers will render the huge image resized down to 10 by 10px.
So, on the line where you alter the height:
thumb.height(config.maxHeight);
the browser goes ahead an also alters the width. If you subsequently read the width (i.e. thumb.width(Math.ceil(thumb.width() / ratio))), you are going to be reading the new width, not the width it had before being given a new height.
var someImg = new Image();
someImg.src = <theURLofDesiredImage>
alert(someImg.width + " : " + someImg.height);
This is not Jquery but its vanilla JS and its a true way to determine "an unloaded" (not cached!) image. Add a query string to the URL url + "?asdasdasdadads" will allow you to circumvent the browser caching the image. This will result in a longer "image load time" but you will ALWAYS and more importantly, PREDICTABLY, resolve the dynamically loaded image.