Rerun javascript function when screen orientation changes - javascript

I'm using a code that scale images to fit the parent div, it's called "aspectcorrect".
The problem happens on the mobile version: my parent div has 100% width, and when the user changes the orientation of the screen to landscape, the image doesn't resize to fit the new div's width.
There is a way to rerun the onload event (which scales the image), when the user changes the orientation of the screen?
Here is my website: www.mcsoftware.com.br/sitemc
I'm still working on it.
(To understand what I'm saying, open it on your cellphone, and when you change the screen orientation just click on "Continuar mesmo assim" to navigate)
Thanks!
aspectcorrect.js
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = { width: 0, height: 0, fScaleToTargetWidth: true };
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
}
else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
}
else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
onimageload.js
function OnImageLoad(evt) {
var img = evt.currentTarget;
// what's the size of this image and it's parent
var w = $(img).width();
var h = $(img).height();
var tw = $(img).parent().width();
var th = $(img).parent().height();
// compute the new size and offsets
var result = ScaleImage(w, h, tw, th, false);
// adjust the image coordinates and size
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
Where onload function goes
<img onload="OnImageLoad(event);" />
https://jsfiddle.net/ffxeqq21/

You can try some javascript library like jQuery mobile and use the orientationchange event This way you could just do
$( window ).on( "orientationchange", function( event ) {
//Some code
});

Related

Keeping iframe/image ratio when resizing on height

I managed to keep the iframe's ratio for when the user resizes the window on width, but I have trouble adding the logic for when the user resizes the window on height due to conflicting logic, since the resize on width already alters the height of the iframe.
This is the function that gets called when resizing:
function calculateAspectRatioFit(width, height, ratio) {
if(height) {
let width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
} else if(width) {
let height = ((width)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
}
But I believe that the problem lies in the trigger:
const resizeHandler = (e) => {
console.log("inside ", parseInt(iframeHeight), iframeElement.offsetHeight);
if(parseInt(iframeWidth) > iframeElement.offsetWidth) {
// overwrite inline styling
iframeElement.style.cssText = 'height: ' + calculateAspectRatioFit(iframeElement.offsetWidth, null, iframeRatio) + 'px!important';
} else if (parseInt(iframeHeight) > window.innerHeight) {
iframeElement.style.cssText = 'width: ' + calculateAspectRatioFit(null, iframeElement.offsetHeight, iframeRatio) + 'px!important';
}
}
Got any solutions for this? (pen below)
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011
Solved, as per the codepen (link is the same as the one in the original post):
Added a container for the iframe (if you are using a modal, that can be the container):
const resizeHandler = (e) => {
// get container measures
let computedContainerStyling = getComputedStyle(iframeContainer);
let containerWidth = parseInt(computedContainerStyling.width);
let containerHeight = parseInt(computedContainerStyling.height);
if ( (containerWidth / iframeRatio) > containerHeight){
iframeHeight = containerHeight;
iframeWidth = containerHeight * iframeRatio;
} else {
iframeWidth = containerWidth;
iframeHeight = containerWidth / iframeRatio;
}
iframeElement.style.width = Math.floor(iframeWidth) + 'px';
iframeElement.style.height = Math.floor(iframeHeight) + 'px';
}
window.addEventListener('resize', resizeHandler, false);
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011

Using jQuery Pan and Zoomooz together to pan and zoom DOM element

Seen a few similar questions on here but most seem to refer to zooming and panning images, I can't find anything that answers my problem.
I'm looking to create something like https://timmywil.com/panzoom/demo/, but I want to have a DOM element zoom on click, then pan around on mouse move.
I've been able to come up with something that's very nearly there, example here. https://jsfiddle.net/kevngibsn/5okxr8n3/29/
For this I'm using Zoomooz to handle the zoom, and jQuery Pan to take care of the panning. The issue with this example is that jQuery Pan works out the size of the DOM element on page load and doesn't take into account the increased size after zoom, so mouse move doesn't pan to the edges.
Here's the code from jQuery Pan:
(function( $ ){
var getSize = function($element) {
return {
'width': $element.width(),
'height': $element.height()
};
};
var toCoords = function(x, y) {
return {'x': x, 'y': y};
};
var vectorsEqual = function(v1, v2) {
return v1.x == v2.x && v1.y == v2.y;
}
$.fn.pan = function(options) {
//Container is element this plugin is applied to;
//we're pan it's child element, content
var container = this;
var content = this.children(':first');
//Precalculate the limits of panning - offset stores
//the current amount of pan throughout
var offset = toCoords(
Number(content.css('left').replace('px', '')) | 0,
Number(content.css('top').replace('px', '')) | 0
);
var containerSize = getSize(container);
var contentSize = getSize(content);
var minOffset = toCoords(
-contentSize.width + containerSize.width,
-contentSize.height + containerSize.height
);
var maxOffset = toCoords(0, 0);
//By default, assume mouse sensitivity border
//is 25% of the smallest dimension
var defaultMouseEdge = 0.25 * Math.min(
containerSize.width,
containerSize.height
);
var settings = $.extend( {
'autoSpeedX' : 0,
'autoSpeedY' : 0,
'mouseControl' : 'kinetic',
'kineticDamping' : 0.8,
'mouseEdgeSpeed' : 5,
'mouseEdgeWidth' : defaultMouseEdge,
'proportionalSmoothing' : 0.5,
'updateInterval' : 50,
'mousePan' : null
}, options);
//Mouse state variables, set by bound mouse events below
var mouseOver = false;
var mousePanningDirection = toCoords(0, 0);
var mousePosition = toCoords(0, 0);
var dragging = false;
var lastMousePosition = null;
var kineticVelocity = toCoords(0, 0);
//Delay in ms between updating position of content
var updateInterval = settings.updateInterval;
var onInterval = function() {
if (container.hasClass('pan-off')) return false; //Temporarily disabling pan add/remove class pan-off
var mouseControlHandlers = {
'edge' : updateEdge,
'proportional' : updateProportional,
'kinetic' : updateKinetic
};
var currentHandler = settings.mouseControl;
if(!mouseControlHandlers[currentHandler]()) {
//The handler isn't active - just pan normally
offset.x += settings.autoSpeedX;
offset.y += settings.autoSpeedY;
}
//If the previous updates have take the content
//outside the allowed min/max, bring it back in
constrainToBounds();
//If we're panning automatically, make sure we're
//panning in the right direction if the content has
//moved as far as it can go
if(offset.x == minOffset.x) settings.autoSpeedX = Math.abs(settings.autoSpeedX);
if(offset.x == maxOffset.x) settings.autoSpeedX = -Math.abs(settings.autoSpeedX);
if(offset.y == minOffset.y) settings.autoSpeedY = Math.abs(settings.autoSpeedY);
if(offset.y == maxOffset.y) settings.autoSpeedY = -Math.abs(settings.autoSpeedY);
//Finally, update the position of the content
//with our carefully calculated value
content.css('left', offset.x + "px");
content.css('top', offset.y + "px");
}
var updateEdge = function() {
if(!mouseOver) return false;
//The user's possibly maybe mouse-navigating,
//so we'll find out what direction in case we need
//to handle any callbacks
var newDirection = toCoords(0, 0);
//If we're in the interaction zones to either
//end of the element, pan in response to the
//mouse position.
if(mousePosition.x < settings.mouseEdgeWidth) {
offset.x += settings.mouseEdgeSpeed;
newDirection.x = -1;
}
if (mousePosition.x > containerSize.width - settings.mouseEdgeWidth) {
offset.x -= settings.mouseEdgeSpeed;
newDirection.x = 1;
}
if(mousePosition.y < settings.mouseEdgeWidth) {
offset.y += settings.mouseEdgeSpeed;
newDirection.y = -1;
}
if (mousePosition.y > containerSize.height - settings.mouseEdgeWidth) {
offset.y -= settings.mouseEdgeSpeed;
newDirection.y = 1;
}
updateMouseDirection(newDirection);
return true;
}
var updateProportional = function() {
if(!mouseOver) return false;
var rx = mousePosition.x / containerSize.width;
var ry = mousePosition.y / containerSize.height;
targetOffset = toCoords(
(minOffset.x - maxOffset.x) * rx + maxOffset.x,
(minOffset.y - maxOffset.y) * ry + maxOffset.y
);
var damping = 1 - settings.proportionalSmoothing;
offset = toCoords(
(targetOffset.x - offset.x) * damping + offset.x,
(targetOffset.y - offset.y) * damping + offset.y
)
return true;
}
var updateKinetic = function() {
if(dragging) {
if(lastMousePosition == null) {
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
kineticVelocity = toCoords(
mousePosition.x - lastMousePosition.x,
mousePosition.y - lastMousePosition.y
);
lastMousePosition = toCoords(mousePosition.x, mousePosition.y);
}
offset.x += kineticVelocity.x;
offset.y += kineticVelocity.y;
kineticVelocity = toCoords(
kineticVelocity.x * settings.kineticDamping,
kineticVelocity.y * settings.kineticDamping
);
//If the kinetic velocity is still greater than a small threshold, this
//function is still controlling movement so we return true so autopanning
//doesn't interfere.
var speedSquared = Math.pow(kineticVelocity.x, 2) + Math.pow(kineticVelocity.y, 2);
return speedSquared > 0.01
}
var constrainToBounds = function() {
if(offset.x < minOffset.x) offset.x = minOffset.x;
if(offset.x > maxOffset.x) offset.x = maxOffset.x;
if(offset.y < minOffset.y) offset.y = minOffset.y;
if(offset.y > maxOffset.y) offset.y = maxOffset.y;
}
var updateMouseDirection = function(newDirection) {
if(!vectorsEqual(newDirection, mousePanningDirection)) {
mousePanningDirection = newDirection;
if(settings.mousePan) {
settings.mousePan(mousePanningDirection);
}
}
}
this.bind('mousemove', function(evt) {
mousePosition.x = evt.pageX - container.offset().left;
mousePosition.y = evt.pageY - container.offset().top;
mouseOver = true;
});
this.bind('mouseleave', function(evt) {
mouseOver = false;
dragging = false;
lastMousePosition = null;
updateMouseDirection(toCoords(0, 0));
});
this.bind('mousedown', function(evt) {
dragging = true;
return false; //Prevents FF from thumbnailing & dragging
});
this.bind('mouseup', function(evt) {
dragging = false;
lastMousePosition = null;
});
//Kick off the main panning loop and return
//this to maintain jquery chainability
setInterval(onInterval, updateInterval);
return this;
};
})( jQuery );
I'd at about my limit on this one, any advice on how to get that panning the whole element?

Canvas Zoom-in, Zoom-Out using mousewheel

I'm trying make my <canvas> zoomable (zoom-in, zoom-out).
I'm trying the following code to take care of the zooming functions, however, it does not work as expected because as soon as I try to zoom-in/out, the canvas goes empty/blank.
This leads me to believe the mousewheel function is working but something is off as it "deletes" the canvas drawing.
function drawZoom() {
var startScale = 1;
var scale = startScale;
var floor = $("#floorplan")[0].getContext("2d")
var width = floor.canvas.width;
var height = floor.canvas.height;
var intervalId;
var imageData = floor.getImageData(0, 0, width, height);
var canvas = $("<canvas>").attr("width", width).attr("height", height)[0];
canvas.getContext("2d").putImageData(imageData, 0, 0);
function drawContents(){
var newWidth = width * scale;
var newHeight = height * scale;
floor.save();
floor.translate(-((newWidth-width)/2), -((newHeight-height)/2));
floor.scale(scale, scale);
floor.clearRect(0, 0, width, height);
floor.drawImage(canvas, 0, 0);
floor.restore();
}
$("#test").on('DOMMouseScroll mousewheel',function(e) {
var e = e || window.event; // old IE support
var theEvent = e.originalEvent.wheelDelta || e.originalEvent.detail*-1;
if(theEvent / 120 > 0) {
zoomin();
} else {
zoomout();
}
if (e.preventDefault)
e.preventDefault();
});
function zoomin()
{
scale = scale + 0.01;
drawContents();
}
function zoomout()
{
scale = scale - 0.01;
drawContents();
}
}
CodePen Live Example
What am I doing wrong here? How can I solve this?
I can add the wheel hanlder in your drawSettings like this:
//Drag settings start
function drawSettings() {
//snip....
if (canvas.addEventListener) {
// IE9, Chrome, Safari, Opera
canvas.addEventListener("mousewheel", MouseWheelHandler, false);
// Firefox
canvas.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
}
// IE 6/7/8
else canvas.attachEvent("onmousewheel", MouseWheelHandler);
//the rest of your code...
The function to zoom in and out needs to be tailored for your example by using the value of delta. Add this function I found from here: https://www.sitepoint.com/html5-javascript-mouse-wheel/ and alter the canvas size as needed.
function MouseWheelHandler(e) {
// cross-browser wheel delta
var e = window.event || e; // old IE support
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
canvas.style.width = Math.max(50, Math.min(800, canvas.width + (30 * delta))) + "px";
canvas.style.height = Math.max(50, Math.min(800, canvas.width + (30 * delta))) + "px";
return false;
}

How to make script resize images and divs on window resize and orientation change

I am currently using the following javascript to resize an image to the size of it's parent, while maintaining aspect ratio and keeping the parent div square. So i have a square box with a rectangle stretched to either the max width or max height depending on orientation. This works great on first load however I cannot get the images and divs to resize on page orientation change or resize to work. Any ideas. I have tried using the window.resize and window.orientation listeners.
Original code was from:
Scale, crop, and center an image...
var aspHt = $('.aspectcorrect').outerWidth();
$('.aspectcorrect').css('height', aspHt + 'px').css('width', aspHt + 'px');
function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {
var result = {
width : 0,
height : 0,
fScaleToTargetWidth : true
};
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
} else {
fScaleOnWidth = !fLetterBox;
}
if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
} else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth - result.width) / 2);
result.targettop = Math.floor((targetheight - result.height) / 2);
return result;
}
function RememberOriginalSize(img) {
if (!img.originalsize) {
img.originalsize = {
width : img.width,
height : img.height
};
}
}
function FixImage(fLetterBox, div, img) {
RememberOriginalSize(img);
var targetwidth = $(div).width();
var targetheight = $(div).height();
var srcwidth = img.originalsize.width;
var srcheight = img.originalsize.height;
var result = ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox);
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetleft);
$(img).css("top", result.targettop);
}
function FixImages(fLetterBox) {
$("div.aspectcorrect").each(function(index, div) {
var img = $(this).find("img").get(0);
FixImage(fLetterBox, this, img);
});
}
window.onload = function() {
FixImages(true);
};
Call .resize() after $(window).resize():
$(window).resize( function(){
var height = $(window).height();
var width = $(window).width();
if(width>height) {
// Landscape
$("#landscape").css('display','none');
} else {
// Portrait
$("#landscape").css('display','block');
$("#landscape").click(function(){
$(this).hide();
});
}
}).resize();
I figured out what I was missing. The first bit of javascript is setting the style of height and width. When recalling the .outerHeight it was still using the inline style to calculate the width, and hence not resizing the div. I simply used .removeAttr('style') to remove that property first and then did the resize. Working now. I simply used $(window).on("resize", resizeDiv) and wrapped my resizing into a function named resizeDiv
function resizeDiv() {
var asp = $('.aspectcorrect');
asp.removeAttr("style");
var aspHt = asp.outerWidth();
asp.css('height', aspHt + 'px').css('width', aspHt + 'px');
FixImages(true);
}

How to display part of an image for the specific width and height?

Recently I participated in a web project which has a huge large of images to handle and display on web page, we know that the width and height of images end users uploaded cannot be control easily and then they are hard to display. At first, I attempted to zoom in/out the images to rearch an appropriate presentation, and I made it, but my boss is still not satisfied with my solution, the following is my way:
var autoResizeImage = function(maxWidth, maxHeight, objImg) {
var img = new Image();
img.src = objImg.src;
img.onload = function() {
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth == 0 && maxHeight == 0) {
Ratio = 1;
} else if (maxWidth == 0) {
if (hRatio < 1) {
Ratio = hRatio;
}
} else if (maxHeight == 0) {
if (wRatio < 1) {
Ratio = wRatio;
}
} else if (wRatio < 1 || hRatio < 1) {
Ratio = (wRatio <= hRatio ? wRatio : hRatio);
}
if (Ratio < 1) {
w = w * Ratio;
h = h * Ratio;
}
w = w <= 0 ? 250 : w;
h = h <= 0 ? 370 : h;
objImg.height = h;
objImg.width = w;
};
};
This way is only intended to limit the max width and height for the image so that every image in album still has different width and height which are still very urgly.
And right at this minute, I know we can create a DIV and use the image as its background image, this way is too complicated and not direct I don't want to take. So I's wondering whether there is a better way to display images with the fixed width and height without presentation distortion?
Thanks.
I would recommend taking a look at something like twitter bootstraps carousel. In this they use an image tag within a div and size it by setting the image properties to something like
img {
height: auto;
max-width: 100%;
}
You can see a small example in this little fiddle.
By setting height to auto it will keep the ratio intact.
By setting max-width: 100% it will not zoom in the image past it's original size.
I solved this problem follow the following steps:
1, Write a method to zoom in/out the image to the appropriate width and height you want:
var autoResizeImage = function(targetWidth, targetHeight, objImg) {
if (0 >= targetWidth || 0 >= targetHeight) {
// Ilegal parameters, just return.
return;
}
var img = new Image();
img.src = objImg.src;
// Calculate the width and height immediately the image is loaded.
img.onload = function() {
var hRatio;
var wRatio;
var width = img.width;
var height = img.height;
var calcWidth = width;
var calcHeight = height;
wRatio = targetWidth / width;
hRatio = targetHeight / height;
if (wRatio < hRatio) {
calcWidth = targetWidth;
calcHeight = (targetHeight / height) * targetHeight;
} else {
calcHeight = targetHeight;
calcWidth = (targetWidth / width) * targetWidth;
}
objImg.width = calcWidth;
objImg.height = calcHeight;
};
};
and then call this method in its onload event like
<img src='PATH' onload='autoResizeImage(740, 460, this)'/>
2, Create a DIV outside of this image and style the width and height that you want to image displays with:
<div style='width: 740px; height: 460px; overflow:hidden;'></div>
And then the image would display with the fixed width and height you set.
Thanks for my friends from this site.

Categories