Need to fit application width to device width - javascript

What do i have?
Web app(just html,css,js), application has fixed width and height (1024*768);
Android application created with cordova by web application;
Testing android application on htc desire 500 (android version 4.1.2)
Problem:
I need width of application fit to device width on all android devices. Now my application is bigger then device width.
What i tried to do?
Changed viewport meta tag in different ways like
<meta name="viewport" content="width=device-width, user-scalable=no" />
Used javascript to change app zoom (on deviceredy event)
var contentWidth = document.body.scrollWidth,
windowWidth = window.innerWidth,
newScale = windowWidth / contentWidth;
document.body.style.zoom = newScale;
Used javascript to change viewport
var ww = (jQuery(window).width() < window.screen.width) ?
jQuery(window).width() : window.screen.width;
// min width of site
var mw = 1020;
//calculate ratio
var ratio = ww / mw;
if (ww < mw) {
jQuery('meta[type="viewport"]').attr('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=yes, width=' + ww);
} else {
jQuery('meta[type="viewport"]').attr('content', 'initial-scale=1.0, maximum-scale=2, minimum-scale=1.0, user-scalable=yes, width=' + ww);
}
But solutions that i describe above can`t help. Do anyone knows solution that can help do that i need?

I have solved problem by using css transform, this css property is similar to zoom but it is supported by all modern browsers.
Notice: This solution appropriate just for fixed size layouts
Function that i wrote to solve my problem (Just put body as element, and it initial size as height and width):
/**
* #param {string} element - element to apply zooming
* #param {int} width - initial element width
* #param {int} height - initial element heigth
* #param {float} desiredZoom - which zoom you need, default value = 1
*/
function zoomElement(element, width, height, desiredZoom) {
desiredZoom = desiredZoom || 1;
var zoomX = (jQuery(window).width() * desiredZoom) / width,
zoomY = (jQuery(window).height() * desiredZoom) / height,
zoom = (zoomX < zoomY) ? zoomX : zoomY;
jQuery(element)
.css('transform', 'scale(' + zoom + ')')
.css('transform-origin', '0 0')
// Internet Explorer
.css('-ms-transform', 'scale(' + zoom + ')')
.css('-ms-transform-origin', '0 0')
// Firefox
.css('-moz-transform', 'scale(' + zoom + ')')
.css('-moz-transform-origin', '0 0')
// Opera
.css('-o-transform', 'scale(' + zoom + ')')
.css('-o-transform-origin', '0 0')
// WebKit
.css('-webkit-transform', 'scale(' + zoom + ')')
.css('-webkit-transform-origin', '0 0');
// Center element in it`s parent
(function () {
var $element = jQuery(element);
// Remove previous timeout
if ($element.data('center.timeout')) {
console.log("clear timeout");
clearTimeout($element.data('center.timeout'));
}
var timeout = setTimeout(function () {
$element.data('center.timeout', timeout);
var parentSize = {
'height' : $element.parent().height(),
'width' : $element.parent().width()
},
rect = element.get(0).getBoundingClientRect();
element.css({
'marginTop' : 0,
'marginLeft' : 0
});
// Center vertically
if (parentSize.height > rect.height) {
var marginTop = (parentSize.height - rect.height) / 2;
element.css('marginTop', marginTop);
}
// Center horizontally
if (parentSize.width > rect.width) {
var marginLeft = (parentSize.width - rect.width) / 2;
element.css('marginLeft', marginLeft);
}
}, 300);
})();
}

Related

Re-sizing Image Width Using JavaScript

I am trying to re-size an image in a popup. The original image is 6000 x 4000. I do a check to see if the image is greater than 500, and if so I just try and set the image to 500. Trying to set it using 'this', makes the pop open in a tab and the image is still its original size. If I try and set the image not using 'this', the pop up works as intended regarding where it is positioned on screen and the size of the box, but the image, is still its original size--6000 x 4000. (PS: I have to use ES5 as well.)
What gives?
Thanks,
CM
<script language="javascript" type="text/javascript"><!--
// let i=0;
function resize() {
console.log("Testing");
let i=0;
if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1 && window.navigator.userAgent.indexOf('SV1') != -1) {
i=30; //This browser is Internet Explorer 6.x on Windows XP SP2
} else if (window.navigator.userAgent.indexOf('MSIE 6.0') != -1) {
i=0; //This browser is Internet Explorer 6.x
} else if (window.navigator.userAgent.indexOf('Firefox') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=25; //This browser is Firefox on Windows
} else if (window.navigator.userAgent.indexOf('Mozilla') != -1 && window.navigator.userAgent.indexOf("Windows") != -1) {
i=45; //This browser is Mozilla on Windows
} else {
i=80; //This is all other browsers including Mozilla on Linux
}
var imgWidth = document.images[0].width;
var imgHeight = document.images[0].height;
console.log("Original image width is: " + imgWidth);
console.log("Original image height is: " + imgHeight);
if(imgWidth > 500){
//Shrink the image to size of popup frame
this.imgWidth = 500;
this.imgHeight = 500;
console.log("Adjusted image width is: " + imgWidth);
console.log("Adjusted image height is: " + imgHeight);
//Get display/screen width and height
var screenWidth = screen.width;
var screenHeight = screen.height;
console.log("Screen width is: " + screenWidth);
console.log("Screen height is: " + screenHeight);
//Set popup position on display/screen
var leftpos = screenWidth / 2 ;
var toppos = screenHeight / 2 - imgHeight / 2;
console.log("Left position is: " + leftpos);
console.log("Top position is: " + toppos);
//Set popup frame width and height equal to adjusted image width and height
var frameWidth = imgWidth;
var frameHeight = imgHeight+i;
console.log("Frame width is: " + frameWidth);
console.log("Frame height is: " + frameHeight);
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth,frameHeight+i);
}
else if (document.documentElement && document.documentElement.clientWidth) {
var imgHeight = document.images[0].height + 40 - i;
var imgWidth = document.images[0].width + 20;
var height = screen.height;
var width = screen.width;
var leftpos = width / 2 - imgWidth / 2;
var toppos = height / 2 - imgHeight / 2;
frameWidth = imgWidth;
frameHeight = imgHeight + i;
window.moveTo(leftpos, toppos);
window.resizeTo(frameWidth, frameHeight + i);
} else if (document.body) {
window.resizeTo(document.body.clientWidth, document.body.clientHeight - i);
}
self.focus();
}//end resize() function
//--></script>
Use
var imgWidth = document.images[0].style.width;
instead of
var imgWidth = document.images[0].width;

Scaling and centering SVG with JS

Learning SVG / snap. With some help I can pull a region from a map and load it onto a modal per the fiddle here.
I am now trying to keep the SVG within a 200px by 200px div, maintaining its aspect ratio, and to scale, so each region in the modal will fit in the above box but remain to scale against other regions.
var m = Snap('#world-map');
var d = Snap('#svg-region');
var regionSVG = m.select('#' + region);
var p = regionSVG.clone();
d.append(p);
var bb = regionSVG.getBBox();
var vb = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
d.attr({
viewBox: vb
})
I tried processing the data in the bbox to create a scale, but failed miserably.
function zoomBBox(bbox)
{
var zbbox, ratio, diffx, diffy;
var length = 200;
if (bbox.width > bbox.height) {
ratio = bbox.width / length;
zbbox.width = length;
zbbox.height = bbox.height * ratio;
} else {
ratio = bbox.height / length;
zbbox.width = bbox.width * ratio;
zbbox.height = length;
}
diffx = (zbbox.width - length) / 2;
diffy = (zbbox.height - length) / 2;
zbbox.x = bbox.x + diffx;
zbbox.y = bbox.y + diffy;
return zbbox;
}
just add
.modal-body svg {
max-width: 100%;
max-height: 100%;
}
https://jsfiddle.net/0djhebes/7/
You just need the power of CSS :D
You need to define in the SVG #svg-region inside the modal via css HEIGHT & WIDTH that you want that they appear at their maximum.
For example 100px & 100px and they will be rendered inside that box
#svg-region{width:100px; height:100px;}
For aligning it, use a as wrapper around #svg-region with the following css (I think that should work, didn't test it to align vertically and horizontally)
.wrapper{display:flex; jusfity-alignment:center; align-item:center;}

converting accelerometer/gyroscope values to x/y

I'm using document.mousemove to animate a gradient. I'd like to use the same function on mobile devices with an accelerometer/gyroscope, but I can't seem to translate the values.
I've tried various equations but can't seem to get things to work.
Here's my JS:
$(document).mousemove(function(event) {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);
$('.radial-gradient').css('background', 'radial-gradient(at ' + mouseXpercentage + '% ' + mouseYpercentage + '%, #72c0d4, #03373d)');
});

Resize in firefox not working

Can someone tell me why resizing does not work in firefox but it works in internet explorer? I cannot figure out how to force it in all browsers. I am trying to resize the width to 800 and height to 475. Then I am trying to make it where you can not maximize the browser (disabling it). As well as removing all toolbars from showing and URL as well.
function OpenWindow(url, width, height)
{
var features = 'resizable:no;status:yes;dialogwidth:' + width + 'px;dialogheight:' + height + 'px;help:no';
features = features + ';dialogtop:' + (window.screen.availHeight - height) /2;
features = features + ';dialogleft:' + (window.screen.availWidth - width) /2;
window.showModalDialog(url, this, features);
}
function Resize(width, height)
{
var availWidth = window.screen.availWidth;
var availHeight = window.screen.availHeight;
var top = (availHeight - height) / 2;
var left = (availWidth - width) / 2;
if (window.dialogHeight)
{
window.dialogHeight = height + 'px';
window.dialogWidth = width + 'px';
window.dialogLeft = left;
window.dialogTop = top;
}
else
{
var _win;
if(window.parent) _win = window.parent;
else _win = window;
_win.resizeTo(width, height);
_win.moveTo(left, top);
}
}
Resize(800, 475);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Any advice will help. I do not understand why things work in certain browsers and not in others.
As you can see here, it's not been allowed in Firefox at all since Firefox 7. Sorry but you won't be able to resize the window in Firefox.

Pinch to zoom with CSS3

I'm trying to implement pinch-to-zoom gestures exactly as in Google Maps. I watched a talk by Stephen Woods - "Creating Responsive HTML5 Touch Interfaces” - about the issue and used the technique mentioned. The idea is to set the transform origin of the target element at (0, 0) and scale at the point of the transform. Then translate the image to keep it centered at the point of transform.
In my test code scaling works fine. The image zooms in and out fine between subsequent translations. The problem is I am not calculating the translation values properly. I am using jQuery and Hammer.js for touch events. How can I adjust my calculation in the transform callback so that the image stays centered at the point of transform?
The CoffeeScript (#test-resize is a div with a background image)
image = $('#test-resize')
hammer = image.hammer ->
prevent_default: true
scale_treshold: 0
width = image.width()
height = image.height()
toX = 0
toY = 0
translateX = 0
translateY = 0
prevScale = 1
scale = 1
hammer.bind 'transformstart', (event) ->
toX = (event.touches[0].x + event.touches[0].x) / 2
toY = (event.touches[1].y + event.touches[1].y) / 2
hammer.bind 'transform', (event) ->
scale = prevScale * event.scale
shiftX = toX * ((image.width() * scale) - width) / (image.width() * scale)
shiftY = toY * ((image.height() * scale) - height) / (image.height() * scale)
width = image.width() * scale
height = image.height() * scale
translateX -= shiftX
translateY -= shiftY
css = 'translateX(' + #translateX + 'px) translateY(' + #translateY + 'px) scale(' + scale + ')'
image.css '-webkit-transform', css
image.css '-webkit-transform-origin', '0 0'
hammer.bind 'transformend', () ->
prevScale = scale
I managed to get it working.
jsFiddle demo
In the jsFiddle demo, clicking on the image represents a pinch gesture centred at the click point. Subsequent clicks increase the scale factor by a constant amount. To make this useful, you would want to make the scale and translate computations much more often on a transform event (hammer.js provides one).
The key to getting it to work was to correctly compute the point of scale coordinates relative to the image. I used event.clientX/Y to get the screen coordinates. The following lines convert from screen to image coordinates:
x -= offset.left + newX
y -= offset.top + newY
Then we compute a new size for the image and find the distances to translate by. The translation equation is taken from Stephen Woods' talk.
newWidth = image.width() * scale
newHeight = image.height() * scale
newX += -x * (newWidth - image.width) / newWidth
newY += -y * (newHeight - image.height) / newHeight
Finally, we scale and translate
image.css '-webkit-transform', "scale3d(#{scale}, #{scale}, 1)"
wrap.css '-webkit-transform', "translate3d(#{newX}px, #{newY}px, 0)"
We do all our translations on a wrapper element to ensure that the translate-origin stays at the top left of our image.
I successfully used that snippet to resize images on phonegap, using hammer and jquery.
If it interests someone, i translated this to JS.
function attachPinch(wrapperID,imgID)
{
var image = $(imgID);
var wrap = $(wrapperID);
var width = image.width();
var height = image.height();
var newX = 0;
var newY = 0;
var offset = wrap.offset();
$(imgID).hammer().on("pinch", function(event) {
var photo = $(this);
newWidth = photo.width() * event.gesture.scale;
newHeight = photo.height() * event.gesture.scale;
// Convert from screen to image coordinates
var x;
var y;
x -= offset.left + newX;
y -= offset.top + newY;
newX += -x * (newWidth - width) / newWidth;
newY += -y * (newHeight - height) / newHeight;
photo.css('-webkit-transform', "scale3d("+event.gesture.scale+", "+event.gesture.scale+", 1)");
wrap.css('-webkit-transform', "translate3d("+newX+"px, "+newY+"px, 0)");
width = newWidth;
height = newHeight;
});
}
I looked all over the internet, and outernet whatever, until I came across the only working plugin/library - http://cubiq.org/iscroll-4
var myScroll;
myScroll = new iScroll('wrapper');
where wrapper is your id as in id="wrapper"
<div id="wrapper">
<img src="smth.jpg" />
</div>
Not a real answer, but a link to a plug=in that does it all for you. Great work!
https://github.com/timmywil/jquery.panzoom
(Thanks 'Timmywil', who-ever you are)
This is something I wrote a few years back in Java and recently converted to JavaScript
function View()
{
this.pos = {x:0,y:0};
this.Z = 0;
this.zoom = 1;
this.scale = 1.1;
this.Zoom = function(delta,x,y)
{
var X = x-this.pos.x;
var Y = y-this.pos.y;
var scale = this.scale;
if(delta>0) this.Z++;
else
{
this.Z--;
scale = 1/scale;
}
this.zoom = Math.pow(this.scale, this.Z);
this.pos.x+=X-scale*X;
this.pos.y+=Y-scale*Y;
}
}
The this.Zoom = function(delta,x,y) takes:
delta = zoom in or out
x = x position of the zoom origin
y = y position of the zoom origin
A small example:
<script>
var view = new View();
var DivStyle = {x:-123,y:-423,w:300,h:200};
function OnMouseWheel(event)
{
event.preventDefault();
view.Zoom(event.wheelDelta,event.clientX,event.clientY);
div.style.left = (DivStyle.x*view.zoom+view.pos.x)+"px";
div.style.top = (DivStyle.y*view.zoom+view.pos.y)+"px";
div.style.width = (DivStyle.w*view.zoom)+"px";
div.style.height = (DivStyle.h*view.zoom)+"px";
}
function OnMouseMove(event)
{
view.pos = {x:event.clientX,y:event.clientY};
div.style.left = (DivStyle.x*view.zoom+view.pos.x)+"px";
div.style.top = (DivStyle.y*view.zoom+view.pos.y)+"px";
div.style.width = (DivStyle.w*view.zoom)+"px";
div.style.height = (DivStyle.h*view.zoom)+"px";
}
</script>
<body onmousewheel="OnMouseWheel(event)" onmousemove="OnMouseMove(event)">
<div id="div" style="position:absolute;left:-123px;top:-423px;width:300px;height:200px;border:1px solid;"></div>
</body>
This was made with the intention of being used with a canvas and graphics, but it should work perfectly for normal HTML layout

Categories

Resources