Changing the size of an image within the script? - javascript

So I'm trying to do an onclick image change which worked, but I'd like the second image to be bigger than the first, is this possible?
Here is the JavaScript code (this is the first time I'm trying to use HTML aside from basic things)
function changeImage() {
if (document.getElementById("imgClickAndChange").src == "https://cdn.glitch.com/2191cc92-26e9-4b6e-9beb-428fb7eb3976%2FPicsArt_03-26-03.26.33.png?v=1616763476562")
{
document.getElementById("imgClickAndChange").src = "https://cdn.glitch.com/2191cc92-26e9-4b6e-9beb-428fb7eb3976%2FPicsArt_03-26-03.12.37.png?v=1616764012012";
}
else
{
document.getElementById("imgClickAndChange").src = "https://cdn.glitch.com/2191cc92-26e9-4b6e-9beb-428fb7eb3976%2FPicsArt_03-26-03.26.33.png?v=1616763476562";
}
}
I want to be able to change the size of that second image.

I'm not sure if you mean this but you can change the size of the Image using:
myelement.style.height = size + "px";
myelement.style.width = size + "px";
The size variable is basically the size of the image in pixels.

Related

Get offsetHeight after manipulating DOM

I wrote the following code:
var image_pinch_help = document.getElementById("image_pinch_help");
var pinch_img_el = document.getElementById("pinch_img_el");
function openImage(img_url) {
pinch_img_el.src = img_url;
if (pinch_img_el.complete) {
IMGloaded();
}
else {
pinch_img_el.addEventListener('load', IMGloaded())
pinch_img_el.addEventListener('error', function() {
alert('error')
});
}
image_pinch_help.style.display = "block";
document.getElementById("pinch_values").setAttribute("content", "");
}
function IMGloaded() {
var screen_height = window.screen.height;
console.log("HERE IS THE HEIGHT: " + screen_height);
var img_height = pinch_img_el.offsetHeight;
console.log("HERE IS THE IMAGE: " + img_height);
}
The code starts at the function openImage(). This function is called to open an Image at my webpage. So the image gets the full width of the screen. The screen where the image is shown on is image_pinch_help. You see that I make this screen visible. To allow the user to zoom into the image I am manipulation the HTML DOM, that the user can scroll at the whole page. I do this here: document.getElementById("pinch_values").setAttribute("content", "");.
When the Image loaded I need to get the height of the screen, which works perfectly. But I also need to get the height of the loaded image. The problem is that its always returning an empty string. I read a long time ago that this could be caused by HTML DOM Manipulations.
But how to fix this disaster?
~Marcus

pixijs swapping out an image without it jumping

I am working on a html 5 javascript game. It has a heavily textured background. I am looking at having one 3d background item and swapping it out on the fly. So in this instance we see a room with a closed door - then when a js event is fired - the image is swapped out to show an open door.
I am trying to create the function and although I can swap the image - I am unable to stop it from jumping.
so a new image path comes in - I null and remove the old backdrop and replace it with the new. I have read about adding it to the texture cache - not sure how to do that? Its my first time using pixijs
GroundPlane.prototype.resetBackdrop = function (imagePath) {
if(this.backdrop) {
this.backdrop.alpha = 0;
this.removeChild(this.backdrop);
this.backdrop = null;
this.backdrop = PIXI.Sprite.fromImage(imagePath);
this.backdrop.anchor.x = .5;
this.backdrop.anchor.y = .5;/*
this.backdrop.scale.x = 1.2;
this.backdrop.scale.y = 1.2;*/
this.addChildAt(this.backdrop, 0);
this.backdrop.alpha = 1;
}
};
The reason for the "jump" is that the image being swapped in takes some time to load before it can be displayed on the screen.
To prevent this, you can load the image into the TextureCache ahead of time, so when you swap images, there won't be any delay.
//set the initial backdrop image
this.backdrop = PIXI.Sprite.fromImage("Image1.png");
this.backdrop.anchor.x = 0.5;
this.backdrop.anchor.y = 0.5;
this.backdrop.scale.x = 1.2;
this.backdrop.scale.y = 1.2;
//this will store the second image into the texture cache
PIXI.Texture.fromImage("Image2.png");
//if you need to keep track of when the image has finished loading,
//use a new PIXI.ImageLoader() instead.
GroundPlane.prototype.resetBackdrop = function (imagePath)
{
//Update the image Texture
this.backdrop.setTexture(PIXI.Texture.fromFrame(imagePath));
};

JQuery: How to hide an image until source changed

I have an image that is being resized programmatically, based on the current height/width of the container. My problem is that it shows the image at it's original size before it does the resizing.
See this JSFiddle
You'll notice how it flashes up a stretched image before it fits the image nicely in the middle.
I want to hide the image until that resizing has taken place, but I can't figure out how.
Any suggestions?
JSCode:
function LoadImg(img) {
img.css('visibility','hidden');
var src=img.attr('src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.css('visibility','');
}
Html:
<div class="window">
<img src="http://www.angclassiccarparts.co.uk/image_anysize.aspx?f=/images/ww/panel/service_kits.jpg&w=154&h=154&color=png" id="img" onload="LoadImg($(this));" />
</div>
I've tried hiding with visibility hidden until the function has run, but that doesn't wait for it to load...
You're changing the source of the image, which forces it to load a new image, then you instantly set the image to visible.
Ultimately you want to wait until the second image is loaded before showing it, which can be achieved using .load() like so:
img.on('load', function() {
img.css('visibility','visible');
});
Here's an updated jsFiddle with the working code: http://jsfiddle.net/ev4YL/2/
I would, however, recommend a different approach. It doesn't make much sense to load an image, then when it's loaded load another image. Perhaps you should store the dimensions in html data attributes, then load the images dynamically on document.ready.
Something like this could work, if you set each image to have a data-src instead of src to begin with:
$('img').each(function() {
var img = $(this);
var src = img.attr('data-src');
var imgh = img.parent().height();
var imgw = img.parent().width();
var pattern = /&?(w|h)=[^&]+/g;
src = src.replace(pattern, '');
img.attr('src', src + '&w=' + imgw + '&h=' + imgh);
img.on('load', function() {
img.css('visibility','visible');
});
});
And the demo here: http://jsfiddle.net/ev4YL/4/
You can hide the image with display: none until the end of the function, then set the image to display: block (or whatever you need) at the very end. That way the rest of the function has already run, when it displays it will have already been resized.
See JSFiddle
But basically just:
CSS:
img {
display: none;
}
JavaScript:
function loadImg(img) {
----all of your function here----
img.css('display', 'block');
}

Getting original image for cropping, ignoring the width attribute?

My user can upload really big images, and for cropping and display purposes i'm adding width attribute so it will fit well in the browser window. Real image size can be - say 1920 x 1080 px.
<!-- width added for display purpose -->
<img class="croppable" src="images/fhd.jpg" width="640" />
In order to calculate real selection box dimension (if the x coordinate is 20px then would be 60px in the original full hd picture) i need to get the full image size before apply the width attribute.
The problem is that this will return 640 as value, taking into account the width attribute:
// Important: Use load event to avoid problems with webkit browser like safari
// when using cached images
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.width);
});
});
Please don't flag this as duplicate since what i'm asking is completly different from simple image width/height retrival (which works, actually).
EDIT: Chris G. solution seems not working:
$(window).load(function(){
$('img.croppable').each(function(){
console.log(this.src);
var original = new Image(this.src);
console.log(original);
$("#original_w").text(original.width); // Temp, more images to be added
$("#original_h").text(original.height); // Temp, more images to be added
});
});
Console output:
http://localhost/DigitLifeAdminExtension/images/pillars-of-creation.jpg
<img width="0">
Get the width/height of the image itself, not the div it is contained within.
$(window).load(function(){
$('img.croppable').each(function(){
var img = new Image();
img.src = $(this).src;
alert(img.width);
});
});
You can remove the attributes, get the width and put the attributes in place again:
var $img = $(img);
var oldWidth = $img.attr("width");
var imgWidth = $img.removeAttr("width").width();
$img.width(oldWidth);
But I think Chris G.'s answer works well too, just making sure it will be loaded when you try to get the width:
img.onload = function() {
if (!img.complete) return; // IMG not loaded
width = img.width;
imgManipulationGoesHere();
}
Works in most up-to-date browsers and IE9.
$(window).load(function(){
$('img.croppable').each(function(){
alert(this.naturalHeight);
});
});
The working solution would be:
$(function(){
$('img.croppable').each(function () {
var original = new Image(this.src);
original.onload = function () {
alert(original.src + ': ' + original.width + 'x' +original.height);
};
});
});

How can I change an image with another keeping aspect ratio?

I have the following HTML code:
<img id="Card00" src="images/words/back.png" onclick="imageClicked(0,0);">
And the following Javascript code:
function ShowImage(id, row, column)
{
var imagePath = 'images/words/' + id + '.png';
var imgId = '#Card' + row + '' + column;
$(imgId).attr('src', imagePath);
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
if (width > height)
$(imgId).attr('width', 200);
else
$(imgId).attr('height', 200);
}
imageClicked only calls ShowImage.
Back.png is 200x200. I want to change back.png image with another one. That another one (id + .png), is bigger than 200x200, so I need to resize it on ShowImage function.
But I can't do that, because I can't get its new width and height in this piece of code:
var width = $(imgId).attr('width');
var height = $(imgId).attr('height');
My goal is to change back.png image with another one, keeping aspect radio.
And there is another problem: first I see the bigger image, and then, sometimes, it gets 200x200. I said sometimes because sometimes I get its width or its height.
Any advice?
The best thing to do is just load the image into memory first, then once it loads get its real height and width, use that info -- URL, height and width -- to determine the appropriate dimensions. Note that this isn't foolproof, though, as caching can mess it up.
Note that you can generalize the below to include maximum dimensions in the function itself, but I think it's pretty easily adaptable:
// Example: replaceImage($("img#someID"), "http://example.com/logo.png");
var MAX_HEIGHT = 80;
var MAX_WIDTH = 80;
function keepAspectRatio(temp, $target, url) {
// Get height and width once loaded
var realHeight = temp.height;
var realWidth = temp.width;
// Get how much to divide by (1 if image fits in dimensions)
// Get rid of ", 1" if you just want everything to be either
// MAX_HEIGHT tall or MAX_WIDTH wide
var factor = Math.max(realHeight/MAX_HEIGHT, realWidth/MAX_WIDTH, 1);
realHeight /= factor;
realWidth /= factor;
// Set the target image's source, height and width
$target.attr("src", url).css({height: realHeight, width: realWidth});
}
function replaceImage($target, url) {
$("<img>").load(function() {
keepAspectRatio(this, $target, url);
}).attr("src", url);
}
jsFiddle Example
EDIT
Swapped places of attr and load per the comment below. I'm not going to go too crazy with optimization beyond that, as what we'd really do if we wanted things perfect would be to preload everything, get its real dimensions, and use that information each time we change the original image.
Did you try:
var width = $(imgId).clientWidth;
var height = $(imgId).clientHeight;

Categories