paper.setup changes the canvas size? Bug in PaperJS? - paperjs

when I do
paper.setup(imageCanvas);
the width and height of imageCanvas changes from 2048 * 1536 to 681 * 511 I tried to to understand the code by debugging it and
_setViewSize: function(size) {
var element = this._element,
pixelRatio = this._pixelRatio,
width = size.width,
height = size.height;
element.width = width * pixelRatio;
element.height = height * pixelRatio;
if (pixelRatio !== 1) {
if (!PaperScope.hasAttribute(element, 'resize')) {
var style = element.style;
style.width = width + 'px';
style.height = height + 'px';
}
this._context.scale(pixelRatio, pixelRatio);
}
},
is the area where it changes the size of the element by multiplying it by pixelRatio, which is somehow 0.3330000042915344.
Can anybody explain why paperjs would try to change the dimensions?

This is hilarious!
I figured out why the pixelRatio is 0.333... it is because I zoomed out the browser and hence it was changing the canvas size.

Related

How to measure/convert CSS text margin/padding in the Photoshop?

How to get CSS text margin/padding from the Photoshop?
or
How to convert the distance from/to the text in Photoshop into CSS margin/padding?
Distances from text elements (paragraphs) in Photoshop do not correspond to margins/paddings in the CSS. Distances are measured, for example, using smart guides:
All because the line height is not used in the distances calculation. Therefore, the first recommendation I found is to use the formula:
margin_in_CSS = distance_in_PS - (line-height - font-size) / 2
or shorter:
CSS = PS - (line-height - font-size) / 2
This is the distance from some obvious border (line) to the text element. For the distance between two paragraphs we use, respectively:
CSS = PS - (line-height_1 - font-size_1) / 2 - (line-height_2 - font-size_2) / 2
As the font size increases, it becomes clear that this formula is not enough. The actual height of the line (obtained with the selection tool) in Photoshop is even less than the font size!
Although the photoshop still considers the height of the element to be approximately equal to the font size, which does not affect the distance to it :(. For example, on the Properties tab:
I calculated that the difference between the real height of the line and the font size is about 30% or 15% at the top and bottom of the text (I'm not saying this is 100% true!). And now I use the formula:
CSS = PS - (0.15 * font-size + (line-height - font-size) / 2)
Or between two paragraphs:
CSS = PS - (0.15 * font-size_1 + (line-height_1 - font-size_1) / 2)
- (0.15 * font-size_2 + (line-height_2 - font-size_2) / 2)
Similarly, we can not rely on the correct definition of the height of a paragraph in several lines by Photoshop. But here the situation is simpler, the real height of the paragraph in the CSS will be:
height = line-height * num_of_lines
The question is, is there a simpler way? О_о
Sorry for my English ^_^
UPDATE, shorter formulas:
text <> border
CSS = PS - (line-height - 0.7 * font-size) / 2
text <> text
CSS = PS - (line-height_1 - 0.7 * font-size_1) / 2
- (line-height_2 - 0.7 * font-size_2) / 2
UPDATE:
Now a script is being developed for the correct calculation of distances on the Adobe forum (link). At the moment, the script can calculate the distance from the bounding box of the text line with a standard (auto) line-height of 120%.
UPDATE:
It does not matter if you use a pointed text or a paragraph text, the result bounding box height is not equal to the text line-height (leading)
How to convert the distance from/to the text in Photoshop into CSS margin/padding?
The actual resulting glyph(s) (pink border in your image) of your text will have different height with the following contents:
"
[empty space] = no glyph at all
...
a
A
Qq
q
Margins and paddings should not be measured from the text itself, but from the boundaries of text line (or line-height in CSS).
In the above example:
65px is the actual height of text line (or line-height in CSS), (the distance from two text baselines when the text wraps) and what is used when calculating margin/padding. The end result being that no matter the contents of your text element, the distance from its baseline to the element following it should remain the same, based on line-height, (bottom) margin and (bottom) padding (and, of course, on the top margin and padding of next element).
To answer your question in a nutshell, PS does not apply a reduction to margins. It's just they are not calculated from the bounding box of the text glyphs (which might vary depending on contents), but from the bounding box of text line.
Another thing to consider when converting from .psd to HTML is that in HTML you have collapsing margins. In short, from two vertical adjacent margins only the largest one will be kept. If the other one is negative, it will be deducted from the positive one and if both are negative, the one with the largest value will be applied.
Finally, the script for measuring vertical distance is finished!
It can correctly calculate the vertical distance for CSS between layers, one of which or both are text layers.
Here's the link on Adobe Forums - A script for measuring the distance between two elements?
// version no CS6 or no effects
var old_units = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
try { app.activeDocument.suspendHistory("Get Text Bounds", "var bounds = get_selected_layers_bounds()") } catch(e) { alert(e); }
try { executeAction( charIDToTypeID( "undo" ), undefined, DialogModes.NO ); } catch(e) { alert(e); }
app.preferences.rulerUnits = old_units;
if (bounds)
{
if (bounds.length == 2)
{
var distance = 0;
if (bounds[0].bottom <= bounds[1].top) distance = bounds[1].top - bounds[0].bottom;
else if (bounds[1].bottom <= bounds[0].top) distance = bounds[0].top - bounds[1].bottom;
else alert("Intersecting layers")
var distance_in_css = distance - (bounds[0].leading - 1.2*bounds[0].size)/2 - (bounds[1].leading - 1.2*bounds[1].size)/2;
alert("distance = " + distance + "\ndistance_in_css = " + distance_in_css);
}
else
alert("More then 2 selected layers")
}
else
alert("There is no selected layers")
/////////////////////////////////////////////////////////////////////////////////////////////////
function get_selected_layers_bounds()
{
try {
var ref = new ActionReference();
ref.putProperty( charIDToTypeID( "Prpr" ), stringIDToTypeID( "targetLayers" ) );
ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
var desc = executeActionGet(ref);
if (!desc.hasKey( stringIDToTypeID("targetLayers") ) ) return null;
var n = 0;
try { activeDocument.backgroundLayer } catch (e) { n = 1; }
desc = desc.getList( stringIDToTypeID("targetLayers"));
var len = desc.count;
var selected_bounds = new Array();
for (var i = 0; i < len; i++)
{
try
{
var r = new ActionReference();
r.putIndex( charIDToTypeID( "Lyr " ), desc.getReference(i).getIndex() + n);
var ret = executeActionGet(r);
var size = 0;
var leading = 0;
if (ret.hasKey(stringIDToTypeID("textKey")))
{
var textStyleRangeList = ret.getObjectValue(stringIDToTypeID("textKey")).getList(charIDToTypeID("Txtt" ));
if (textStyleRangeList.count > 1) { alert("More than one textStyleRange in layer", "Oops!!"); }
var textStyle = textStyleRangeList.getObjectValue(0).getObjectValue(charIDToTypeID("TxtS" ));
var auto_leading = textStyle.getBoolean(stringIDToTypeID("autoLeading"));
size = textStyle.getUnitDoubleValue(stringIDToTypeID("size"));
leading = auto_leading?size*1.2:textStyle.getUnitDoubleValue(stringIDToTypeID("leading"));
var s = ret.getObjectValue(stringIDToTypeID("textKey")).getString(charIDToTypeID("Txt " ));
s = s.replace(/^./gm, String.fromCharCode(0x2588));
var d1 = new ActionDescriptor();
d1.putReference( charIDToTypeID( "null" ), r );
var d2 = new ActionDescriptor();
d2.putString( charIDToTypeID( "Txt " ), s);
d1.putObject( charIDToTypeID( "T " ), charIDToTypeID( "TxLr" ), d2 );
executeAction( charIDToTypeID( "setd" ), d1, DialogModes.NO );
ret = executeActionGet(r);
}
// var bounds = ret.getObjectValue(stringIDToTypeID("bounds")); // use this in CS6 or when you want to take into account the effects
var bounds = ret.getObjectValue(stringIDToTypeID("boundsNoEffects")); // in CS6 does not work
var obj = {
left : bounds.getUnitDoubleValue(stringIDToTypeID("left")),
top : bounds.getUnitDoubleValue(stringIDToTypeID("top")),
right : bounds.getUnitDoubleValue(stringIDToTypeID("right")),
bottom : bounds.getUnitDoubleValue(stringIDToTypeID("bottom")),
size : size,
leading: leading,
};
selected_bounds.push(obj);
}
catch (e) { alert(e); return null; }
}
return selected_bounds;
}
catch (e) { alert(e); return null; }
}
The script should be saved as a *.js or *.jsx file (for example, distance.js) in the Photoshop folder - C:\Program Files\Adobe\Adobe Photoshop CC 2017\Presets\Scripts
It will be available in the Photoshop menu - File > Scripts > Distance
it does not matter , psd is for showing how the website looks on completion you have to take in consideration the font size , for e.g. for paragraph text if the font size is 14 pt in psd and the grid is 1200px (bootstrap) than you have to convert the font in aspect ratio of browser ( default 16px now in bootstrap ) and calculate accordingly like 14pt in psd is equals to 14px + (14 * 0.16%)px in browser and everything else accordingly , similar for line height.
also if you want to set font size same as psd its up to you select 14px for html if our psd font size is 14pt for paragraph.

CSS: Element fixed to viewport height, scaled proportionally, centered

I have elements which have a set height of 100% viewport height. Inside of these are a background image which is also fixed to the same height - so the image's top and bottom are always visible, it's centered, and sometimes it's edges get cut off.
What I'm trying to add on top of this is another element which matches the same behavior of the background image (to place other things over the image, but ensure they always line up).
I have a working example using Javascript, but wondering if this same behavior could be replicated with CSS. The pinkish box is the element which I am scaling based on the viewport's size and it should always match up with the background image behind it.
https://jsfiddle.net/louiswalch/p1rkohzt/
And all the scaling logic is as follows:
var $window = $(window);
var base_width = 1600;
var base_height = 960;
var base_ratio = (base_width / base_height);
var contents = $('SECTION .content');
$window.on('resize', function() {
var window_width = $window.width();
var window_height = $window.height();
var window_ratio = (window_height / window_height);
var scaled_width = (window_height * 100/base_height) * base_width/100;
contents.css({
width: (scaled_width+'px'),
height: (window_height+'px'),
marginLeft: ('-'+scaled_width/2+'px'),
});
}).trigger('resize');

How to scale text size compared to container

How would you scale text size based on container size. Other questions state it can't be done with css, if not how would you go about it?
Here is a way to set the text to fit the width of the container. It works by incrementally increasing the font size of a hidden div until it is smaller than the width of the container for which you want to text to fit inside. It then sets the font size of the container to that of the hidden div.
This is a little inefficient and could be optimized by caching the old width of the container, then incrementing from the old font size to either larger or smaller values based on how the width of the container changed.
jsFiddle: http://jsfiddle.net/sarathijh/XhXQk/
<div class="scale-text styles">
This is a test of scaling text to fit the container. Lorem Ipsum Dolor Sit Amet.
</div>
<div id="font-metrics"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var fontMetrics = document.getElementById('font-metrics');
var scaleTexts = $('.scale-text');
$(window).on('resize', updateFontSize);
updateFontSize();
function updateFontSize()
{
scaleTexts.each(function()
{
var $scaleText = $$(this);
fontMetrics.innerHTML = this.innerHTML;
fontMetrics.style.fontFamily = $scaleText.css('font-family');
fontMetrics.style.fontWeight = $scaleText.css('font-weight');
fontMetrics.style.fontStyle = $scaleText.css('font-style');
fontMetrics.style.textTransform = $scaleText.css('text-transform');
var fontSize = 50; // max font-size to test
fontMetrics.style.fontSize = fontSize + 'px';
while ($$(fontMetrics).width() > $scaleText.width() && fontSize >= 0)
{
fontSize -= 1;
fontMetrics.style.fontSize = fontSize + 'px';
}
this.style.fontSize = fontSize + 'px';
});
}
/**
* A simple caching function for jQuery objects.
*/
function $$(object)
{
if (!object.jquery)
object.jquery = $(object);
return object.jquery;
}
</script>
You should be able to do this using jQuery -- something like..
$('#cooldiv').css('font-size', '100%')
and
$("#cooldiv").animate({
'width' : (xWidth * (35 / 100)) + 'px',
'minWidth' : (xWidth * (35 / 100)) + 'px',
'maxWidth' : (xWidth * (35 / 100)) + 'px',
'fontSize' : (xWidth * (35 / 100)) + '%'
}, 1000);
I couldn't work out how to do it with CSS, so I used pure JS (don't need jquery).
var els = document.getElementsByClassName('abc')
for (var i = 0; i < els.length; i++){
els[i].style.fontSize = els[i].clientHeight + 'px'
}
Example: http://jsfiddle.net/nickg1/H64mQ/
Here's how I accomplished it- I wrapped the text in a span and scaled that down with a CSS transform:
<div id="fit-text-in-here">
<span>Scale this text to fit inside the parent div.</span>
</div>
jQuery:
$(function(){
var textWidth = $('#fit-text-in-here span').width(),
fitWidth = $('#fit-text-in-here').width();
if (textWidth > fitWidth) {
var scaleTo = fitWidth / textWidth,
offset = (fitWidth - textWidth)/2;
$('#fit-text-in-here span').css({
'-moz-transform': 'scale('+scaleTo+')',
'-webkit-transform': 'scale('+scaleTo+')',
'-o-transform': 'scale('+scaleTo+')',
'transform': 'scale('+scaleTo+')',
'margin-left': offset,
'display': 'inline-block'
});
}
});

Adobe Flex Mobile Stage size

How would I go about finding the display size and position of the stage or navigator area in Adobe Flex mobile? I would like to be able to make something the exact width and height (without using 100% w&h). And position the top at the top of the stage. I'm sure this description isn't the easiest to understand, so hopefully this image will help:
protected function init(event:FlexEvent):void
{
if (NativeMaps.isSupported){
NativeMaps.service.addEventListener(Event.ACTIVATE, mapReady2);
//NativeMaps.service.addEventListener(NativeMapEvent.MAP_CREATED, mapReady);
try{
NativeMaps.service.mapOptions.compassEnabled=true;
NativeMaps.service.mapOptions.zoomControlsEnabled = true;
NativeMaps.service.mapOptions.zoomGesturesEnabled = true;
NativeMaps.service.mapOptions.rotateGesturesEnabled = true;
NativeMaps.service.mapOptions.myLocationButtonEnabled = true;
}catch(e:Error){
}
var tla:ViewNavigatorApplication=FlexGlobals.topLevelApplication as ViewNavigatorApplication;
var width:Number = tla.width;
var height:Number = tla.height-tla.actionBar.height;
var x:Number = 0;
var y:Number = tla.actionBar.height;
NativeMaps.service.createMap(width,height,x,y);
}
}
I think this is what you need:
var tla :ViewNavigatorApplication = FlexGlobals.topLevelApplication as ViewNavigatorApplication;
var width :Number = tla.width;
var height :Number = tla.height=tla.actionBar.height;
var x :Number = 0;
var y :Number = tla.actionBar.height;
Then size your component using the width and height and position it using the x and y values. I wrote this in the browser, so expect typos in code. There may be some padding issues that make the sizes / positioning slightly off but you'll have to try it and see what you get.

Background-size cover jumping when background-position switches to fixed

I am working on a Parallax/Scrolling Timeline project and I am having a problem with the CSS3 Background-size cover property.
The div has these properties:
background: url(../images/timeline/back-6.jpg) no-repeat top center black;
background-size: cover;
padding-top: 90px;
height: 1855px;
position: relative;
Using jQuery I switch the background-attachment to fixed. When I do this the background image jumps "in" (meaning that parts of the image that were past the edge of the screen are now visible). Which isn't the desired result.
In testing I can switch the div to use background-size: 100% cover but it is causing different vertical jumping issues when scrolling.
Any ideas of how to prevent it from jumping in when I switch the background to fixed? (It also happens in reverse when I set the background to scroll).
I sadly can't link to a demo of this code as the page isn't ready to be deployed yet.
I had the same issue, when setting background-size to cover or contain
Setting a fixed height, in example for smaller screens via #media prevents the background-image from jumping. After my tests I came to the conclusion, that the jumping is due to the orientation of the element after setting background-attachment to fixed
Setting it to fixed, the size is calculated by the size of the viewport, not the element containing the background-image. This is where the jumping comes from and why setting a fixed height or width for the background-size solves this issue.
I had the same problem while creating a one page layout i wanted to use with a scrollTo-Plugin and so on....
The page layout was devided in two parts:
Left side for the background image which should change/scroll with the content on the right side.
So i used to make a kind of jquery Plugin to combine both "background-position: fixed" and "background-size: cover".
you just need to define the element by class/id for aligning the background-images.
dont complain about the code. im relatively new to javascript/jquery. but its working ;)
there it is:
function fixedResize() {
var targetEl = $('element where bg-images are in');
var targetWidth = targetEl.width();
var targetHeight = targetEl.height();
var targetPosX = targetEl.offset().left;
var targetPosY = targetEl.offset().top;
var leftRatio = targetWidth / targetHeight;
//console.log('TargetWidth', targetWidth, 'TargetHeight', targetHeight, 'Offset', targetPosX, targetPosY, 'leftRatio', leftRatio);
targetEl.each(function(){
var imgTarget = $(this);
var url = $(this).css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />'); // make background-image as image tag for getting width and height of the image
imgTarget.css('background-attachment','fixed');
bgImg.hide();
bgImg.bind('load', function(){
var imgHeight = $(this).height();
var imgWidth = $(this).width();
var imgRatio = imgWidth / imgHeight;
$(this).remove(); // remove img Tags again
// Calculate resize dimensions
if (imgRatio > leftRatio) {
var currentWidth = imgRatio * targetHeight; // image width after resize
var currentHeight = (currentWidth/imgWidth)*imgHeight;
var setToLeft = ((currentWidth - targetWidth)/2);
var imgPosX = targetPosX - setToLeft;
var imgPosY = (currentHeight - targetPosY - currentHeight/2 - targetHeight/2)* -1;
var resizeImg = 'background-size: auto '+ targetHeight +'px;';
} else if (imgRatio < leftRatio){
var currentWidth = targetWidth;
var currentHeight = (currentWidth/imgWidth)*imgHeight;
var imgPosX = targetPosX;
var imgPosY = (currentHeight - targetPosY - currentHeight/2 - targetHeight/2)* -1;
var resizeImg = 'background-size: '+ targetWidth +'px auto;'; // resize background
}
imgTarget.attr('style','background-attachment: fixed; background-position: '+ imgPosX +'px '+ imgPosY +'px;' + resizeImg);
console.log('imgWidth', imgWidth, 'imgHeight', imgHeight, 'imgRatio', imgRatio, 'currentWidth', currentWidth, 'currentHeight', currentHeight, 'setToLeft', setToLeft);
console.log('imgPos', imgPosX, imgPosY, 'setToLeft', setToLeft, targetPosX);
});
$(this).append(bgImg);
bgImg.attr('src', url);
});
}
fixedResize(); // initiate function
$(window).resize(function() {
fixedResize(); // initiate function for window resize (Fluid behavior)
});
or
jsfiddle.net/rowphant/eXb6e/14/

Resources