I have a div of known size and a link to some image with random size, which i want to show inside this div. I would like an image to have proportional scaling, to be as big as posible, but no bigger than div (either the image width should equal the div's width or the image height should equal the div's height, but i dont exactly know which case).
How could i do it using only html, css, javascript and jquery?
And it would be great not to read the image size.
You can do this with pure CSS by setting max-width and max-height to 100%. This is a great article to read on the subject: http://unstoppablerobotninja.com/entry/fluid-images. The article also discusses how to deal with older versions of IE.
Here's an example of the CSS in action - http://jsfiddle.net/JamesHill/R7bAA/
HTML
<div id='div1'>
<img class='myImageClass' src='http://www.google.com/intl/en_com/images/srpr/logo3w.png' />
</div>
<br />
<div id='div2'>
<img class='myImageClass' src='http://www.google.com/intl/en_com/images/srpr/logo3w.png' />
</div>
CSS
#div1
{
height:100px;
width:200px;
background-color:Gray;
border: 1px solid Black;
}
#div2
{
height:500px;
width:100px;
background-color:Gray;
border: 1px solid Black;
}
.myImageClass
{
max-height:100%;
max-width:100%;
}
Here's a javascript method that computes the aspect ratio of image and container and sets the corresponding height or width value that will first hit the edge and the image then scales the other dimension proportionally:
// pre-cache image
var img1 = new Image();
img1.src = "http://photos.smugmug.com/photos/344291068_HdnTo-L.jpg";
var img2 = new Image();
img2.src = "http://photos.smugmug.com/photos/344291068_HdnTo-L.jpg";
function placeImage(imgObj, containerID) {
var container = $(containerID);
var imageAspectRatio = imgObj.height / imgObj.width;
var containerAspectRatio = container.height() / container.width();
// figure out which dimension hits first and set that to match
if (imageAspectRatio > containerAspectRatio) {
imgObj.style.height = container.height() + "px";
} else {
imgObj.style.width = container.width() + "px";
}
container.append(imgObj);
}
$("#go").click(function() {
placeImage(img1, "#container1");
placeImage(img2, "#container2");
});
You can see it here in this jsFiddle: http://jsfiddle.net/jfriend00/5K3Zf/
Related
I have a div which holds an image. The image itself is loaded in later :
HTML :
<div id="image_holder" class='hide'>
<img id="image" onload="createStimuli() " >
<canvas id="canvasOverImage" class="coveringCanvas" ></canvas>
</div>
coveringCanvas style :
CSS:
.coveringCanvas {
position:relative;
z-index:2
}
Next, when the time is right I load in the image.
document.getElementById('image').src = `imagesource`;
Because now the image is loaded, it triggers createStimuli():
function createStimuli() {
var image = $('#image');
var canvas = $('#canvasOverImage');
canvas.css({top:`-${image.height()}px`}); // set style via css
canvas.attr({ "height":image.height(), "width" :image.width()}); // set attr in html
}
This code places the canvas exactly on top of the image (as intended) But it appears that before the position is changed to be on top, it is placed below or next to the image, stretching the canvas.
As a result, even though the canvas is on the image, the creation of the canvas stretches the div leaving empty space below/next to the div.
Is there a way to counter this? Or should i just resize the div after creating the canvas?
To work around this issue :
First set your image_holder div's position to relative . to make sure all absolute positionned elemnt will be positioning to this last .
Then make canvas position to absolute and left postion to 0
#canvasOverImage {
position:absolute;
}
You can test below snippet i've added some borders to canva to see result
document.getElementById('image').src = "https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg";
function createStimuli() {
var image = $('#image');
var canvas = $('#canvasOverImage');
//canvas.css({top:-(image.height()+5)+'px'}); // set style via css
canvas.attr({ "height":image.height(),"width" :image.width()});
}
#image_holder {
position:relative;
}
#canvasOverImage {
border:1px solid red;
position:absolute;
}
#canvasOverImage {
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image_holder" class='hide'>
<img id="image" onload="createStimuli() " ><!--
--><canvas id="canvasOverImage" class="coveringCanvas" ></canvas>
</div>
Note that i've just remove 5 px to fit exactely image and remove extra space between image and canvas
You could accomplish such thing in a more efficient manner by doing it using the following way ...
document.getElementById('image').src = "https://s-media-cache-ak0.pinimg.com/736x/52/30/66/523066972863437c1a5daa774d1e5414.jpg";
function createStimuli(e) {
var canvas = $('#canvasOverImage')[0];
// set canvas css style
canvas.style.marginLeft = -(e.width + 3) + 'px'; // 3 ~ border width
// set canvas attr in html
canvas.width = e.width;
canvas.height = e.height;
// draw text on canvas *proves canvas is on top*
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.font = 'bold 18px Arial';
ctx.fillText('hello', 10, 25);
}
.coveringCanvas {
border: 3px solid black;
}
.hide {
display: flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image_holder" class='hide'>
<img id="image" onload="createStimuli(this)">
<canvas id="canvasOverImage" class="coveringCanvas"></canvas>
</div>
In my application i have div that styled with twitter bootstrap like this :
<div class="col-md-12">
<canvas id="canvas"></canvas>
</div>
the canvas is placeholder of some large images.i need a way to scale image to width and height of this div or if not exactly scale to width and height of div , scale must create a very small scroll bar for div. the div has overflow:scroll style.
If you'd like a non-javascript answer, you can make this happen in CSS:
.col-md-12{
position:relative; //make sure this is part of your col-md style
}
#canvas{
position:absolute;
width:100%;
height:100%;
top:0px;
}
I'm assuming that there is styling that is setting the height of your .col-md-12 div elsewhere.
Get the width and height of the div using JavaScript and then set the canvas height and width with these values.
For instance:
var canvas = document.getElementsByTagName('canvas')[0];
var divHeight = document.getElementById('yourDiv').clientHeight;
var divWidth = document.getElementById('yourDiv').clientWidth;
canvas.height = divHeight;
canvas.width = divWidth;
You could add this to a resize event handler so when the div height/width scales it invokes the above code.
As you're using bootstrap, you can do it with jquery:
var $canvas = $("#canvas");
var $parent = $canvas.parent();
$canvas.width($parent.width());
$canvas.height($parent.height());
So Far:
The image is shown on the browser, but it is not resized.
<html>
<img id="banner" src="c:/Users/Name/Downloads/picture.jpg" alt="banner" />
<Script>
var X = screen.width;
var Y = screen.height;
banner = document.getElementById('banner');
banner.style.width = X + 'px';
banner.style.height = (Y/5) + 'px';
</Script>
</html>
Other Attempts:
Show the image using purely javascript
Width and height variables accessed through javascript
First, try with no size specs
Image is not shown when I use:
document.write("<img src='c:/Users/Name/Downloads/picture.jpg' />")
Future Thoughts:
My next attempt will be trying to pass the javascript width and height variables to the html since it seems that the html image always shows and given the right size specifications, then that would be exactly what I want. I will post that here if I find a successful method.
markup and CSS like this should do trick for you.
<div class="banner"></div>
div
{
background:url(https://www.google.com/images/srpr/logo11w.png) no-repeat left top;
width:100%;
height:200px;
background-size:cover;
}
Or even better you can try this CSS instead of above
div
{
position:fixed;
left:0px;
right:0px;
top:0;
height:250px;
background:url(https://www.google.com/images/srpr/logo11w.png) no-repeat center center;
}
I'm trying to develop a slide gallery with image tooltips according to this design:
What I need to develop is a slider controlled by two buttons, each time a button is pressed the slider's content must move a width of the slider or the width of the content left on that side, whichever is smaller. Upon mouse entering an image inside the slider the full-size version must be displayed as a tooltip.
Here's a fiddle of my solution so far, the problem I'm having is that images that don't fully fit into view plus the hidden area to the left get moved to a new line. You can see the problem by clicking the
"Show content size" button, the width of the content element will be equal to the width of the container element + content element's margin-left.
Bonus points if you can suggest an algorithm for moving the content to the right, I've got left figured out to a T (or so I think, anyway), but right is going to take a little more work (it doesn't check whether the end of the content has been reached). Update: It seems I can't implement proper movement to the right until the other issue is resolved, here's the algorithm I came up with, I can't measure "left to display" if I can't measure the actual width of the content element.
I created something you might like:
gallery demo
The gallery does not scroll the full gallery width by default (you can change that) cause some initially cut-off images at the right side, after a 'full' slide would result cut-off again, just on the other side of our gallery. You have for that cause the beKind variable. Adjust it as you like.
It hides the buttons if there's not enough content to make the gallery usable.
The gallery calculates the remaining space to scroll.
Once the slider end reached - the left/right buttons make the gallery jump to the beginning/end, so that are always usable. (Seems kinda weird to have a button... but that does nothing right? ;) )
The Tooltip has a hover-intent built in, to not piss off our users if they unintentionally hovered our gallery: (the tooltip fades in if the hover is registered for more that 120ms. Fair timing. I like it.)
As pointed out in your comment now the tooltip will not go off the screen.
jQ:
// Slide Kind Gallery - by roXon // non plugin v. // CC 2012.
$(window).load(function(){
var galW = $('#gallery').outerWidth(true),
beKind = 120, // px substracted to the full animation to allow some images to be fully visible - if initially partly visible.
sumW = 0;
$('#slider img').each(function(){
sumW += $(this).outerWidth(true);
});
$('#slider').width(sumW);
if(sumW <= galW){ $('.gal_btn').remove(); }
function anim(dir){
var sliderPos = Math.abs($('#slider').position().left),
rem = dir ==='-=' ? rem = sumW-(sliderPos+galW) : rem = sliderPos,
movePx = rem<=galW ? movePx = rem : movePx = galW-beKind;
if( movePx <= 10){
movePx = dir==='-=' ? movePx=rem : movePx = galW-sumW;
dir = '';
}
$('#slider').stop(1).animate({left: dir+''+movePx },1000);
}
$('.gal_btn').on('click', function(){
var doit = $(this).hasClass('gal_left') ? anim('+=') : anim('-=');
});
});
And the tooltip script:
// Addon // Tooltip script
var $tt = $('#tooltip');
var ttW2 = $tt.outerWidth(true)/2;
var winW = 0;
function getWW(){ winW = $(window).width(); }
getWW();
$(window).on('resize', getWW);
$('#slider img').on('mousemove',function(e){
var m = {x: e.pageX, y: e.pageY};
if( m.x <= ttW2 ){
m.x = ttW2;
}else if( m.x >= (winW-ttW2) ){
m.x = winW-ttW2;
}
$tt.css({left: m.x-ttW2, top: m.y+10});
}).hover(function(){
$clon = $(this).clone();
var t = setTimeout(function() {
$tt.empty().append( $clon ).stop().fadeTo(300,1);
},120);
$(this).data('timeout', t);
},function(){
$tt.stop().fadeTo(300,0,function(){
$(this).hide();
});
clearTimeout($(this).data('timeout'));
});
HTML
(Place the #tooltip div after the body tag)
<div id="tooltip"></div>
<div id="gallery_container">
<div id="gallery">
<div id="slider">
<img src="" alt="" />
<img src="" alt="" />
</div>
</div>
<div class="gal_left gal_btn">◀</div>
<div class="gal_right gal_btn">▶</div>
</div>
CSS:
/*GALLERY*/
#gallery_container{
position:relative;
margin:0 auto;
width:600px;
padding:0 30px; /*for the buttons */
background:#eee;
border-radius:5px;
box-shadow: 0 2px 3px #888;
}
#gallery{
position:relative;
height:100px;
width:600px;
overflow:hidden;
}
#slider{
position:absolute;
left:0px;
height:100px;
}
#slider img{
height:100.999%; /* fixes some MOZ image resize inconsistencies */
float:left;
cursor:pointer;
border-right:3px solid transparent; /* instead of margin that could leat to some wrong widths calculations. */
}
.gal_btn{
position:absolute;
top:0px;
width:30px; /*the container padding */
height:40px;
padding:30px 0;
text-align:center;
font-size:30px;
cursor:pointer;
}
.gal_left{left:0px;}
.gal_right{right:0px;}
/* end GALLERY */
/* TOOLTIP ADDON */
#tooltip{
position:absolute;
z-index:100;
width:300px;
padding:10px;
background:#fff;
background: rgba(255,255,255,0.3);
box-shadow:0px 3px 6px -2px #111;
display:none;
}
#tooltip *{
width:100%;
vertical-align:middle;
}
/* end TOOLTIP ADDON */
Hope you'll like it, and you learned some useful UI design tricks.
By the way, if you want to populate your ALT attributes (Search engines like it!) you can also grab that text and make it appear inside the tooltip like here!:
demo with text inside the tooltip
Happy coding.
I don't know if I understand correctly your problem. If you set a width wide enough to .scroll-content div, images wouldn't go to the "next line". So a solution would be to set a width with css. If not, you could use jquery to determine the total width of all the images and give it to the .scroll-content div. Calculate total width of Children with jQuery
I am trying to crop an image from an url and then stretch the cropped image to the available space.
<div style="width:300px; height:400px;">
<img style="width:100%; height:100%;" src="http://www.gravatar.com/avatar/eb95aa803f8c6d536afc87bf8d641ed4?s=128&d=identicon&r=PG" />
</div>
This will stretch the image appropriately, but I do not know how to crop it. I have tried to use clip:rect(0px,60px,200px,0px); but the image will stretch to the available space first and then apply the clip, so it doesn't work for me.
Edit - jsfiddle: http://jsfiddle.net/bjMp6/
For example, I want to try and just crop the head and then stretch the head
Working off of Yoshi's idea without the second div
div
{
width:300px;
height:400px;
border:1px solid #333;
overflow:hidden;
position:relative;
}
img
{
width:300%;
height:300%;
position:absolute;
top:0;
left:-50%;
}
Added the border just to see the containing div. This way you will not need to know the dims of the container but for cropping an image you will have to play with the number with any solution unless all of the images have the same relative composition ie headshots or something similar.
Here's a fiddle for your viewing pleasure.
Also as the container grows/shrinks your image will retain the same crop and position.
I made a fiddle to illustrate the canvas solution :
http://jsfiddle.net/dystroy/mDy24/
Here's the html :
<div id=theimg style="width:300px; height:400px;">
<canvas id=thecanvas style="width:100%;height:100%;">
</div>
And the js :
var img = new Image();
img.src = "http://www.gravatar.com/avatar/eb95aa803f8c6d536afc87bf8d641ed4?s=128&d=identicon&r=PG";
img.onload = function() {
var can = document.getElementById('thecanvas');
var con = can.getContext("2d");
console.log(con);
con.drawImage(img, 0, 0, 50, 50, 0, 0, can.width, can.height);
}