JavaScript: Image doesn't scale in IE when dynamically added - javascript

when I dynamically add an image to a div the image doesn't scale when you resize the window in Internet Explorer.
I think it's more clear if I show two really simple examples:
The following example doesn't use JavaScript it's just plain html and it does what I want.
http://www.friendly-stranger.com/halp/ie-width/index.html
The next one uses JavaScript and if you resize the width of your browser window the image doesn't scale only the width gets smaller.
http://www.friendly-stranger.com/halp/ie-width/bad.html
This is a screenshot of both examples:
(source: friendly-stranger.com)
The JavaScript code I use:
<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
$('div').append(img);
});
</script>

<script type="text/javascript">
$(function(){
var img = new Image();
img.src = 'Koala.jpg';
img.style.height = 'auto';
$('div').append(img);
});
</script>
try this, i hope it'll work

Related

Background image javascript HTML5 canvas

I'm trying to create a simple game using javascript to run on a simple webpage. For some reason, I can't get it to load a background image. I've searched repeatedly and tried numerous ways but I ended up with a black-white canvas. Please, help me as I'm at my wits end.
Here's my code snippet:
<body>
<!-- Site navigation menu -->
<ul>
<li>Play Game</li>
<li>About</li>
<li>Help</li>
</ul>
<!-- Creating the canvas -->
<canvas id= "gameCanvas" width="600" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var bkGround = new Image();
bgImage.src = '/images/backGround.jpg';
bkGround.onload = function(){
ctx.drawImage(bkGround,69,50);
}​
</script>
Anticipated thanks.
I believe that you may be trying to use the background image before has complted loading but you can also use these approaches with CSS.
You can use CSS and either define in your style block or dynamically set it in JS.
<style>
#gameCanvas{
background-image: url(/images/backGround.jpg);
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
}
</style>
or if prefer in JS:
document.getElementById("gameCanvas").style.background = "url('/images/backGround.jpg')";
NB - make sure the image is access to the browser.
Also check your console for errors if using JS - the JS may be breaking with an error before reaching your code.
Also for a working example see HTML5 Canvas background image
Try loading this in on onload event..and as suggested check console to see if there are any errors.
and what is bgImage ? bgImage.src = '/images/backGround.jpg'; ?
body.onload = RenderImage;
function RenderImage()
{
//Your existing script
}
Try to change bgImage to bkGround. And move setting src property after setting onload callback.
So your code will be:
<canvas id= "gameCanvas" width="600" height="480"></canvas>
<script>
var canvas = document.getElementById("gameCanvas");
var ctx = canvas.getContext("2d");
var bkGround = new Image();
bkGround.onload = function(){
ctx.drawImage(bkGround,69,50);
}​;
bkGround.src = '/images/backGround.jpg';
</script>

Resizing background images

This is really for informational and learning purposes while learning more about JavaScript and CSS. I have a local browser index page that I wanted to rotate the background image onload. After looking around and playing with different solutions, I settled on this for the basic rotate functionality:
<html>
<head>
<script language="javascript" type="text/javascript">
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
document.body.style.background = "url(" + img + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
</script>
</head>
<body onload="rotate()">
</body>
</html>
During the process, before I just set the backgroundSizeas cover to fill the window, I was playing with the idea of resizing the images before setting them as the background image after they are selected from the array.
I have done a lot of searching, and the only real working solutions I have found rely on selecting the element by ID, but that also requires that the image has an ID associated, such as in the IMG property in the HTML code. Here the image is selected and set in the JavaScript with CSS.
I have tried setting the image dimensions with img.width / img.height and img.style.width / img.style.height, as well as a few other random solutions I have come across, but whenever I try to change these the image either does not change or it does not show at all.
function rotate()
{
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var img = imgArray[aImg];
image = rsize(img);
document.body.style.background = "url(" + image + ") no-repeat";
document.body.style.backgroundSize = "cover";
}
function rsize(image)
{
image.style.width = "300px";
image.style.height = "300px";
return image;
}
I know I am probably doing something wrong here. Is there a way, in this circumstance, that I can resize these images? Or is there a better way to construct this?
Thanks in advance.
You must set image.style.width and image.style.height on an actual image DOM object, not on the URL as you are currently trying to do.
As an image object is not used for background images, you can't really directly do what you're trying to do for a background image.
You could use the CSS background-size property, but that is fairly new and is not supported in versions of IE prior to IE9. If you were using that, you would set the actual size for that, not "cover".
You could also use an actual DOM image and then present that DOM image as centered in your page if that's what you're really trying to do.
For example, here's how you create a DOM image object, assign it a URL, set it's size and insert it into your page:
var imgArray = new Array("img1.jpg", "img2.jpg", "img3.jpg");
var aImg = Math.floor(Math.random()*imgArray.length);
var imgURL = imgArray[aImg];
var img = new Image();
img.src = imgURL;
img.style.width = "300px";
img.style.height = "300px";
img.id = "centeredImage";
document.body.appendChild(img);
You could then use CSS to position is in the center of your page if you wanted.
Working demo here: http://jsfiddle.net/jfriend00/jqMtV/
No, you have no <img> elements you could (re)size (btw, they would not need ids to be selectable). Your use of rsize(imgArray[aImg]) operates on the array members, which are strings and not DOM elements, so setting values on their non-existent style property would throw an error.
Yet, you're already on the right way with using the backgroundSize style property. Just don't set it to cover, but to the size you need!
document.body.style.backgroundSize = "300px 300px";
If you would want to use a <img> element, add this at the end of your <body>:
<img src="some.jpg" style="position:fixed; z-index:-1; width:100%; height:100%" />

Detecting image width via JavaScript when maxWidth is used

Consider this code:
var img = new Image();
img.onload = function() {
console.log(this.width);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
document.body.appendChild(img);
This will print out the image width (800) correctly. But if I apply a max-width using CSS:
img {max-width: 400px}
Test case: http://jsfiddle.net/MSjnM/
The JS code above will print out 400 instead. That is a bit confusing, as one would think that the width attribute represents the original image width, not the computed width.
Now to something even more confusing, if I append the image in the onload event after the width detection I get a different result:
var img = new Image();
img.onload = function() {
console.log(this.width);
document.body.appendChild(img);
};
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/9/9a/Gull_portrait_ca_usa.jpg/800px-Gull_portrait_ca_usa.jpg';
Test case: http://jsfiddle.net/MSjnM/2/
This will print out 800 instead, even though the CSS has applied. I assume it’s because the image is appended after I detected the width and that the max-width will be applied as soon as the image is inserted into the DOM.
OK, so if I want to get the original image size, no matter when or if the IMG element is inserted in the DOM or whatever CSS styles has been applied, how would I do that fail-safe?
For me:
in IE9, Opera, Safari(PC), FF and chrome the naturalWidth/naturalHeight-properties return the desired values
http://jsfiddle.net/MSjnM/5/
Load the image independently into a new Image object and get the width there:
var img = new Image();
img.src = 'http://placehold.it/350x150'
console.log(img.width);

Obtain background image width

is possible to get background image width which is defined in CSS?
body {
background-image: url('background.jpg');
}
I need something like this:
window.getComputedStyle(document.body, 'background-width');
var u = window.getComputedStyle(document.body, 'background-image');
u = u.replace(/url\(/, '').replace(/\)/, '');
var w = 0;
var i = new Image();
i.onload = function( ){ w = this.width; alert(w); }
i.src = u;
warning: i have ommitted a case, when body has no background image specified, keep that in mind.
is possible to get background image width which is defined in CSS?
I don't think so, but you should be able to use a little trick : Load the image into an img element as described in this question.
If you do this after the document has been fully loaded, the browser should fetch the image from the cache.
It's impossible to do this directly without some sort of work around.
Use JQuery to detect what image the background has, with the imagesLoaded (recommended) or onImagesLoad plugin.
Use the JQuery Dimensions plugin to get the image size.

remote image properties using jquery

Currently i am trying to get remote image width/height. I am developing a link sharing module something like when you paste a link on facebook, you can see title, description and images.
So i tried using php getimagesize to get image width/height its very slow.
So i am thinking of using jquery solution to get remote image width/height so that i can filter image width less then 100px.
I am new in jquery/javascript
I tried something like
var img = $('#imageID');
var width = img.clientWidth;
var height = img.clientHeight;
$('#info').html(width+'.. height: '+height);
Its not working and return undefined .. height: undefined
Any help is appreciated.
Thank you
Try this:
var img = new Image();
img.src = 'http://your.url.here/image.png';
img.onload = function() {
$('#info').text('height: ' + img.height + ' width: ' + img.width);
};
This approach would let you get the image info without having to have an <img> tag at all. Now, perhaps you want the image to be on the page, so you'd do what #patrick suggests in that case.
If you're trying to get the width and height of the image in the client side, you can use jQuery's .width() and .height() methods.
Example: http://jsfiddle.net/aeBWQ/
$(window).load(function() {
var img = $('#imageID');
var width = img.width();
var height = img.height();
$('#info').html(width+'.. height: '+height);
});
Doing $(window).load() will ensure that the images are loaded before getting the height/width.

Categories