How can I crop an image using only Javascript? - javascript

Is there anyway I can crop an image using raw javascript? I want to be able to have a function that takes an image (html tag or source or whatever) with a certain width, height, offsetX and offsetY and it create a image of the portion specified.
I am not that familiar with HTML5 canvas and the like but I need to support older browsers, so that's not even an option (it sucks I know).
I hope this is clear.
Thanks.

If all you need is to display a portion of the image, use css clip: https://developer.mozilla.org/en/CSS/clip . Works in IE6+ even with JavaScript disabled.
If you need to physically crop the image, and need IE6 support, then your options are Flash or sending the data plus cropping values to a server which returns the cropped image.

Often, it's enough to set the limits for rendering by using CSS styles to make the image appear cropped.
Instead of an img, use a div. Assign the desired size to the div. Set the property background to -x -y url('...url-of-your-image...') no-repeat
Replace x and y with the top/left offset that you want to display.

Try with this:
function crop(img_id, crop_id, x, y, width, height) {
$(crop_id).update('<img id="' + crop_id + '_img" src="' +
$(img_id).getAttribute('src') + '" style="display:none" />');
var scale_x = $(crop_id).getWidth() / width;
var scale_y = $(crop_id).getHeight() / height;
$(crop_id).setStyle({
position: 'relative',
overflow: 'hidden'
});
$(crop_id + '_img').setStyle({
position: 'absolute',
display: 'block',
left: (-x * scale_x) + 'px',
top: (-y * scale_y) + 'px',
width: ($(img_id).getWidth() * scale_x) + 'px',
height: ($(img_id).getHeight() * scale_y) + 'px'
});
}
The problem: needs Jquery, and probably the solution works in IE8+.... do you need for IE6+?

Related

Magnify image using only one image

I'm trying to achieve a very simple objective which is to magnify an image. After some searching on the net, it seems like most of the js scripts out there required two image ( one for thumbnail size and another one for zoom-ed size). I'm wondering if I am only having one image, is it still possible to achieve the zoom effect?
I wish to achieve something like this link jQuery ImageZoom with only one image, of course, in a free edition.
I've recently wrote Magnifier.js, if you don't provide the large image the thumbnail will be used instead
You can use one image to zoom with Magic Zoom - you just reference the same large image in both the src and the href and you use width and height to force the img smaller to the size you want.
For example:
<img src="your-big-image.jpg" width="300" height="150">
This approach is fine, though it isn't recommended because it creates a delay while the large image downloads.
You can use the trial version of Magic Zoom free of charge if you don't mind the message shown in the corner.
there is not any complex codes to be written for this purpose
you only need consider these steps
1.create magnifier glass element and set the image that you want to be magnified as background image then set scale(1.5) or 2 for that(you should consider that your glass element can be say 50px in 50px while your background image is 500px in 500px that is help us do the trick)
2.when your mouse pointer come in picture box the magnifier glass should pursue the pointer thats where jquery come in
3.you should get offset of the pointer then change the background-position of
the magnifier glass at same time.
jquery code would be something like this
$(".mpboxpic").mouseenter(function () {
$("#zoombox").css({ "background": "url('" + $(this).attr("src") + "') no-repeat" })
//با این کد تصویر پس زمینه دارای سایز یکسانی خواهد شد
$("#zoombox").css({ "background-size": $(this).width() + "px " + $(this).height() + "px" })
}).mouseleave(function () {
$("#zoombox").hide()
var tg = $("#zoombox").css("background-image")
px = 0;
py = 0;
})
$(".mpboxpic").mousemove(function (p) {
if (px==0) {
$("#zoombox").fadeIn(200)
}
//با کد های زیر مرکز دایره دقیقا در زیر موس قرار میگیرد
px = p.pageX-$("#zoombox").height()/2
py = p.pageY - $("#zoombox").width() / 2
$("#zoombox").css({ "top": py + "px", "left": px + "px", "position": "absolute" });
var my = p.pageY - ($(this).offset().top + $("#zoombox").height() / 4)
var mx = p.pageX - ($(this).offset().left + $("#zoombox").width() / 4)
var coord = "-" + mx + "px " + " -" + my + "px"
$("#zoombox").css({"background-position":coord})
})
and css
#zoombox{
display:none;
position:absolute;
border:5px solid rgba(248, 243, 243, 0.72);
top:25%;
left:25%;
z-index:5;
height:50px;
width:50px;
border-radius:100px;
pointer-events:none;
transform:scale(2);
}
that mpboxpic is your main picture and zoombox is your html tag as magnifier glass
<div id="zoombox">
</div>

How do I apply the same effect that "background-size: cover" does, on a <img>

I need a <img> to have the smallest possible size without leaving any blank spaces inside a div and it needs to be centralized horizontally and vertically. The size of the image is variable.
So here is an example so you can understand it better:
http://jsfiddle.net/q2c9D/
More info: much like Mikel Ward did, I need the images to fill up the div, so that the background of it is not visible. I made the div background black so it was easier to tell that it is not filling up the div. But I need the images to be centered and to be the smallest size possible without being distorted while filling up the div.
Here is my go
I would set the width to 100%, and remove the height property altogether. This will prevent the image from being distorted
img{
width: 100%;
}
To center the element, I would use this plugin. It makes you do no work, other than to call the function
$("img").center()
Try adding min-width: 100% to the img. Here's an example. It may stretch the picture a little but at the size it is, may not be too noticeable. :)
This will center the image on the page:
img{
margin: 0 auto;
position: relative;
display: block;
}
Just wrap the images in a <div> to position them somewhere on the page.
The way i do it is set the width or height, but only 1 as 100%.
<img width="100%" src=""/>
So I was able to get it working the way I wanted using jQuery. With the following code:
function centerimg(){
$('img').each(function(){
var imgwidth = $(this).width();
var imgheight = $(this).height();
if (imgwidth > imgheight) {
$(this).css({
"height": "100%",
"width": "auto"
});
imgwidth = $(this).width();
$(this).css("margin-left", -.5 * imgwidth + 50 + "px");
} else if (imgheight > imgwidth) {
$(this).css({
"width": "100%",
"height": "auto"
});
imgheight = $(this).height();
$(this).css("margin-top", -.5 * imgheight + 50 + "px");
} else {
$(this).css({
"height": "100%",
"width": "100%"
})
}
})
};
window.onload = centerimg;<code>
The code gets the width and height of the image, so if the image is wider or taller it will properly set the smaller dimension to 100% and the larger one to auto. After that it gets the value of that last one again (since it was re sized with auto) and centers it. Also, if the image is a square it just sets both to 100%.
This way the image will ALWAYS fill up the div and be centered.
Thanks all. Hope this code helps others.

Insert image to DOM resized to 50% of its width/height

So I am trying to insert an image to a page with JavaScript with 50% of its width and 50% of its height.
I do this:
someElement.html('<img src="/path/to/img.jpg" alt="" class="sImg" />');
The sImg class is defined in stylesheet like this:
.sImg{
border: 0;
width: 50%;
height: 50%;
}
Yet the image appears fullsize.
I have also checked via Firebug and the image has width and height both at 50%.
First of all, if you're setting a width and height, you should also include display: block; since inline elements don't generally enjoy being given a set height.
But more importantly, when you express a width (or height) as a percentage, that's a percentage of the parent element, so if the parent is 1000px wide, the image will be 500px wide (regardless of what size the actual image file is).
If you're using JavaScript to determine the current image size and change it, just express the new size in px instead of %.
The CSS you've got means that the width and height should be computed as half the size of the parent container, not the image itself.
What you can do is something like this: create an Image object and give it an "onload" handler. The handler can get reliable size information (because the image will have been loaded), and can then add the image element with the proper size.
var img = new Image();
img.onload = function() {
$(someElement).empty().append($('<img/>', {
src: img.src,
alt: '',
'class': 'sImg',
css: { width: Math.floor(img.width / 2) + 'px', height: Math.floor(img.height / 2) + 'px', display: 'inline-block' } // display should be set as you need it
});
};
img.src = yourUrl;
edit — the eerily knowledgeable Šime Vidas points out that setting the "width" or "height" attribute should make the right thing happen, with the size being reduced appropriately to maintain the aspect ratio.
Does the parent container have a height/width? it maybe that the browser does not know what 50% of x is and what 50% of y is. but if it knew what x and y were then it could apply it. Try
var myWidth = $('.sImg').width(),
myHeight = $('.sImg').height();
myWidth = myWidth / 2;
myHeight = myHeight / 2;
$('.sImg').attr('width', myWidth + 'px').attr('height', myHeight + 'px');
http://api.jquery.com/width/
http://api.jquery.com/height/

How do i make "facebook zoom"

Im making a website, and i love the functionality of this google chrome extension call Facebook Photo Zoom # https://chrome.google.com/extensions/detail/elioihkkcdgakfbahdoddophfngopipi
I think the essential idea behind the extension is when you hover over the thumbnail, it grabs the original image file and displays it in full view. If the image is too big, then it will be position on the corners or the top and bottom bars of the window. If it is not too big, it will float next to the mouse position.
The logic behind it i understand, but the actually coding seems to be a bit daunting. I guess the only parts of it i dont understand is how do you code the positions of the expanded images and make them contract/expand when you move your mouse to the left/right. Thanks
13 zoom jquery plugins in here. Choose the best for your needs:)
on mouseover you create big image with
css({position: 'absolute', left: e.pageX, top: e.pageY})
on mousemove you update the left and top in the same way.
check also:
http://api.jquery.com/event.pageY/
http://api.jquery.com/css/
http://api.jquery.com/event.pageX/
Check out this preview image tooltip which is similar to what that Chrome extension does, but you have to provide it the url to the thumbnail and full sized image. Here is the original blog post.
I modified the script to adjust the image size to fit the distance between the cursor and right browser edge. It's not perfect, but it works. Here is a demo.
/*
* Image preview script
* powered by jQuery (http://www.jquery.com)
*
* written by Alen Grakalic (http://cssglobe.com)
*
* for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
*
*/
this.imagePreview = function(){
/* CONFIG */
xOffset = 10;
yOffset = 20;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$('a.preview').hover(function(e){
this.t = this.title;
this.title = '';
var p, c = (this.t != '') ? '<br/>' + this.t : '';
$('body').append('<p id="preview"><img src="' + this.href + '" alt="Image preview" />' + c + '</p>');
// load image and get size
p = $('#preview');
p
.fadeIn('fast')
.find('img').load(function(){
// get image dimensions after it has been loaded
p.data('widths', [ $(window).width(), p.find('img').width() ]);
// set image to 100% to fit in preview window
$(this).width('100%');
position(e);
});
},
function(){
this.title = this.t;
$('#preview').remove();
});
$('a.preview').mousemove(function(e){
position(e);
});
var position = function(e){
var w, prevw = $('#preview'),
w = $.data( prevw[0], 'widths' );
if ( w ) {
prevw
.css('top', e.pageY + yOffset)
.css('left', e.pageX + xOffset)
.css('max-width', (e.pageX + prevw.outerWidth() > w[0]) ? w[0] - e.pageX - xOffset : w[1] || 'auto' );
}
};
};
// starting the script on page load
$(document).ready(function(){
imagePreview();
});
See the Kabbar Image Zoomer at http://www.ideabonus.com/Kabbar/index.html

How do I get slimbox 2 to auto-resize to fit the screen?

According to the Slimbox2 documentation this function isn't supported. But I was wondering if anyone had encountered any tricks to make this work.
The main concern I have is that some of my images are fairly lengthy, and at low resolution LightBox2 would create an annoying experience for the user.
I recently started to use slimbox2 on my website (http://www.trips.elusien.co.uk) and found that it could benefit from a few modifications:
"slide resize": this makes the size of the slideshow constant, rather than depending on the size of the image (by specifying a pixel size), or you can use a percentage to make the slides larger or smaller in the slideshow. You specify this using 2 new options:
slideWidth: 0, // Initial width of the slide (in pixels or in percent as a string e.g. "50%")
slideHeight: 0, // Initial height of the slide (in pixels or in percent as a string e.g. "50%")
enable the slides to be flipped automatically, rather than manually. You specify this using a new option:
slideInterval: 0, // Interval between flipping slides (in seconds), 0 means no automation.
download the slides from the slideshow.
The first and last features cannot be done with the origal version of slimbox2 since in that version the image is displayed as a BACKGROUND image, rather than using the "IMG" tag.
I have put the Javascript and CSS files on my website. If you want to try them go to my website and click on the "slimbox examples" link, you can download them from here. To see a neat way of using slimbox2 click in the "photoSLide Show" link on the home-page.
Regards Neil
its easy to fix check my code.
find and replace the three lines in slimbox2.js file:
$(image).css({backgroundImage: "url(" + activeURL + ")", visibility: "hidden", display: ""});
$(sizer).width(preload.width);
$([sizer, prevLink, nextLink]).height(preload.height);
with:
/* make sure the image won't be bigger than the window */
window.innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //ie fix
window.innerHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; //ie fix
var winWidth = window.innerWidth-200; //browser width
var winHeight = window.innerHeight-100; //browser height
var my_w = preload.width; //original width
var my_h = preload.height; //original height
// scale width
var scaleW1 = winWidth;
var scaleH1 = (my_h * winWidth) / my_w;
// scale height
var scaleW2 = (my_w * winHeight) / my_h;
var scaleH2 = winHeight;
var scale = (scaleW2 > winWidth);
if (scale) {
reswidth = Math.floor(scaleW1);
resheight = Math.floor(scaleH1);
}
else {
reswidth = Math.floor(scaleW2);
resheight = Math.floor(scaleH2);
}
if ($("p").hasClass("slimboxie")){
$(image).css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader( src='"+ activeURL + "', sizingMethod='scale')", visibility: "hidden", display: ""});
$(sizer).width(reswidth);
$([sizer, prevLink, nextLink]).height(resheight); }
else {
$(image).css({backgroundImage: "url(" + activeURL + ")", backgroundSize: reswidth + "px " + resheight + "px", visibility: "hidden", display: ""});
$(sizer).width(reswidth);
$([sizer, prevLink, nextLink]).height(resheight);
}
im amateur at javascript but i think its working great. I made it work with IE8 also. You only need to insert:
<!--[if IE 8]>
<p class="slimboxie"></p>
<![endif]-->
after loading the image, do this:
$('#lbImage').css('background-size', 'contain');

Categories