Retrieving and setting dynamically loaded image sizes via js - javascript

Consider this javascript code:
const profileImageURL = 'https://api.images.com/image/' + id +'/profile';
let profileImage = [];
async function getProfileImage() {
const response = await fetch(profileImageURL);
profileImage = await response.json();
};
and this svelte template code:
<div class="thumbImg">
{#await getProfileImage()}
<div class='spinnerHolder'
in:fade={{duration: 500}}
out:fade={{duration: 500}}
on:introstart={() => doneLoading = false}
on:outroend={() => doneLoading = true}
>
<svg class="spinner" viewBox="0 0 50 50">
<circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5"></circle>
</svg>
</div>
{:then value}
{#if doneLoading}
<img transition:fade alt='profile-image' src={profileImage.url}/>
{/if}
{/await}
</div>
and css:
.thumbImg {
width: 64px;
height: 64px;
display:inline-block;
background-color: var(--border-color);
border: none;
border-radius: var(--large-radius);
overflow: hidden;
img {
min-width: 64px;
border-radius: var(--large-radius);
border-image-width: 0;
}
}
The above loaded images arrive at different widths and heights. Some portrait and some landscape. They need to all be displayed in a square 1:1 box that is 64px x 64px without white space at the side or the bottom. How can I maintain the aspect ratio of these dynamically loaded images so that they either fill the width or height depending on which is needed ? Ideally they would also be offset so they are centered in the 1:1 box.
Visual Examples of the problem:

Updated answer building on Rich's comment below
You can use the object-fit and object-position CSS properties together to fine tune the way the image is displayed inside its content box:
.thumbImg {
width: 64px;
height: 64px;
display:inline-block;
background-color: var(--border-color);
border: none;
border-radius: var(--large-radius);
overflow: hidden;
img {
height: 64px;
width: 64px;
object-fit: cover; // this will make the image cover the content box, clipping horizontally if the original image is landscape orientation, or vertically if it is portrait orientation
object-position: 50% 50%; // this will center the image in the content box (i.e. clip on the left & right if source is landscape and clip top & bottom if source is portrait)
}
}
With this, you do not need to modify your code any further.
Original answer, using CSS background images
You can achieve the desired positioning by using background image CSS properties rather than an img tag, for example:
.avatar {
height: 64px;
width: 64px;
background-size: cover; // this will make the image cover the div, clipping horizontally if the original image is landscape orientation, or vertically if it is portrait orientation
background-position: 50% 50%; // this will center the image (i.e. clip on the left & right if source is landscape and clip top & bottom if source is portrait)
}
With this, all you have to do is replace your <img> tag with a <div class="avatar"> tag and set the background image source dynamically:
<div class="thumbImg">
{#await getProfileImage()}
<div class='spinnerHolder'
in:fade={{duration: 500}}
out:fade={{duration: 500}}
on:introstart={() => doneLoading = false}
on:outroend={() => doneLoading = true}
>
<svg class="spinner" viewBox="0 0 50 50">
<circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="5"></circle>
</svg>
</div>
{:then value}
{#if doneLoading}
<div
transition:fade
class="avatar"
alt="Profile image"
style="background-image: url('{profileImage.url}')"
/>
{/if}
{/await}
</div>
Of course the downside is that you're not using a native image tag anymore, and maybe this is important to you. On the upside, it works without having to use javascript-based DOM manipulation.

You can either make the images width and height relative to the parent div by using percentage values or just set the images to the required max-width and max-height
.thumbImg {
max-width: 64px;
max-height: 64px;
display:inline-block;
background-color: var(--border-color);
border: none;
border-radius: var(--large-radius);
overflow: hidden;
img {
max-width: 100%; //relative to the parent DIV
border-radius: var(--large-radius);
border-image-width: 0;
}
}

Related

Trasparent text in an html a-href button with a threejs animation in background [duplicate]

Is there any way to make a transparent text cut out of a background effect like the one in the following image, with CSS?
It would be sad to lose all precious SEO because of images replacing text.
I first thought of shadows but I can't figure anything out...
The image is the site background, an absolute positioned <img> tag
It's possible with css3 but it's not supported in all browsers
With background-clip: text; you can use a background for the text, but you will have to align it with the background of the page
body {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
margin:10px;
}
h1 {
background-color:#fff;
overflow:hidden;
display:inline-block;
padding:10px;
font-weight:bold;
font-family:arial;
color:transparent;
font-size:200px;
}
span {
background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
display:block;
}
<h1><span>ABCDEFGHIKJ</span></h1>
http://jsfiddle.net/JGPuZ/1337/
Automatic Alignment
With a little javascript you can align the background automatically:
$(document).ready(function(){
//Position of the header in the webpage
var position = $("h1").position();
var padding = 10; //Padding set to the header
var left = position.left + padding;
var top = position.top + padding;
$("h1").find("span").css("background-position","-"+left+"px -"+top+"px");
});
body {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
margin:10px;
}
h1 {
background-color:#fff;
overflow:hidden;
display:inline-block;
padding:10px;
font-weight:bold;
font-family:arial;
color:transparent;
font-size:200px;
}
span {
background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span>ABCDEFGHIKJ</span></h1>
​
http://jsfiddle.net/JGPuZ/1336/
Although this is possible with CSS, a better approach would be to use an inline SVG with SVG masking. This approach has some advantages over CSS :
Much better browser support: IE10+, chrome, Firefox, safari...
This doesn't impact SEO as spiders can crawl SVG content (google indexes SVG content since 2010)
CodePen Demo : SVG text mask
body,html{height:100%;margin:0;padding:0;}
body{
background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
background-size:cover;
background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
<defs>
<mask id="mask" x="0" y="0" width="100" height="50">
<rect x="0" y="0" width="100" height="40" fill="#fff"/>
<text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
<text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
</mask>
</defs>
<rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>
</svg>
If you aim on making the text selectable and searchable, you need to include it outside the <defs> tag. The following example shows a way to do that keeping the transparent text with the <use> tag:
body,html{height:100%;margin:0;padding:0;}
body{
background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
background-size:cover;
background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
<defs>
<g id="text">
<text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
<text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
</g>
<mask id="mask" x="0" y="0" width="100" height="50">
<rect x="0" y="0" width="100" height="40" fill="#fff"/>
<use xlink:href="#text" />
</mask>
</defs>
<rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>
<use xlink:href="#text" mask="url(#mask)" />
</svg>
There is a simple way to do this with just CSS:
background: black;
color: white;
mix-blend-mode: multiply;
for transparent text on a black background, or
background: white;
color: black;
mix-blend-mode: screen;
for transparent text on a white background.
Put these styles on your text element with whichever background you want behind it.
Example CodePen
Read up on mix-blend-mode and experiment with it to use different colours.
Caveats:
For this to work in chrome, you also need to explicitly set a background colour on the html element.
This works on basically all modern browsers except IE.
It is possible, but so far only with Webkit based browsers (Chrome, Safari, Rockmelt, anything based on the Chromium project.)
The trick is to have an element within the white one that has the same background as the body, then use -webkit- background-clip: text; on the inner element which basically means "don't extend the background beyond the text" and use transparent text.
section
{
background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
width: 100%;
height: 300px;
}
div
{
background: rgba(255, 255, 255, 1);
color: rgba(255, 255, 255, 0);
width: 60%;
heighT: 80%;
margin: 0 auto;
font-size: 60px;
text-align: center;
}
p
{
background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
-webkit-background-clip: text;
}
​
http://jsfiddle.net/BWRsA/
just put that css
.banner-sale-1 .title-box .title-overlay {
font-weight: 900;
overflow: hidden;
margin: 0;
padding-right: 10%;
padding-left: 10%;
text-transform: uppercase;
color: #080404;
background-color: rgba(255, 255, 255, .85);
/* that css is the main think (mix-blend-mode: lighten;)*/
mix-blend-mode: lighten;
}
I just discovered a new way to do this while messing around, I'm not entirely sure how it works ( if someone else wants to explain please do ).
It seems to work very well, and requires no double backgrounds or JavaScript.
Here's the code:
JSFIDDLE
body {
padding: 0;
margin: 0;
}
div {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
width: 100vw;
height: 100vh;
}
body::before {
content: '$ALPHABET';
left: 0;
top: 0;
position: absolute;
color: #222;
background-color: #fff;
padding: 1rem;
font-family: Arial;
z-index: 1;
mix-blend-mode: screen;
font-weight: 800;
font-size: 3rem;
letter-spacing: 1rem;
}
<div></div>
In the near future we can use element() to achieve this
The element() function allows an author to use an element in the document as an image. As the referenced element changes appearance, the image changes as well ref
The trick is to create a common div with text then use element() combined with mask.
Here is a basic example that works only on the latest version Firefox for now.
#text {
font-size:35px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
background:red;
-webkit-mask:
-moz-element(#text) center/contain no-repeat, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
}
<div id="text">
You can put your text here
</div>
<div class="main">
</div>
It will produce the following:
It's reponsive since we rely on basic background properties and we can easily update the text using basic CSS.
We can consider any kind of content and also create patterns:
#text {
font-size:30px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
padding:20px;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
#text span {
font-family:cursive;
font-size:35px;
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
background:red;
-webkit-mask:
-moz-element(#text) 0 0/20% auto, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
}
<div id="text">
Your <span>text</span> here 👍
</div>
<div class="main">
</div>
And why not some animation to create an infinite scrolling text:
#text {
font-size:30px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
padding:20px 5px;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
padding-right:calc(50% - 50px);
background:red;
-webkit-mask:
-moz-element(#text) 0 50%/200% auto content-box, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
animation:m 5s linear infinite;
}
#keyframes m{
to {-webkit-mask-position:200% 50%}
}
<div id="text">
Srolling repeating text here
</div>
<div class="main">
</div>
I guess you could achieve something like that using background-clip, but I haven't tested that yet.
See this example:
http://www.css3.info/wp-content/uploads/2008/03/webkit-backgroundcliptext_color.html
(Webkit only, I don't know yet how to change the black background to a white one)
You can use an inverted / negative / reverse font and apply it with the font-face="…" CSS rule. You might have to play with letter spacing to avoid small white gaps between letters.
If you do not require a specific font, it's simple. Download a likeable one, for example from this collection of inverted fonts.
If you require a specific font (say, "Open Sans"), it's difficult. You have to convert your existing font into an inverted version. This is possible manually with Font Creator, FontForge etc., but of course we want an automated solution. I could not find instructions for that yet, but some hints:
How to convert a bitmap font into a TrueType font (plus yet another way to do that). One would first use ImageMagick commands to render the font glyphs into high-resolution raster images and to invert them, then convert them back to a TrueType font with the above instructions.
Is it possible to invert a font with FontForge or another PGM?
Creating a reverse (white on black) font
You can use myadzel's Patternizer jQuery plugin to achieve this effect across browsers. At this time, there is no cross-browser way to do this with just CSS.
You use Patternizer by adding class="background-clip" to HTML elements where you want the text to be painted as an image pattern, and specify the image in an additional data-pattern="…" attribute. See the source of the demo. Patternizer will create an SVG image with pattern-filled text and underlay it to the transparently rendered HTML element.
If, as in the question's example image, the text fill pattern should be a part of a background image extending beyond the "patternized" element, I see two options (untested, my favourite first):
Use masking instead of a background image in the SVG. As in web-tiki's answer, to which using Patternizer will still add automatic generation of the SVG and an invisible HTML element on top that allows text selection and copying.
Or use automatic alignment of the pattern image. Can be done with JavaScript code similar to the one in Gijs's answer.
I needed to make text that looked exactly like it does in the original post, but I couldn't just fake it by lining up backgrounds, because there's some animation behind the element. Nobody seems to have suggested this yet, so here's what I did: (Tried to make it as easy to read as possible.)
var el = document.body; //Parent Element. Text is centered inside.
var mainText = "THIS IS THE FIRST LINE"; //Header Text.
var subText = "THIS TEXT HAS A KNOCKOUT EFFECT"; //Knockout Text.
var fontF = "Roboto, Arial"; //Font to use.
var mSize = 42; //Text size.
//Centered text display:
var tBox = centeredDiv(el), txtMain = mkDiv(tBox, mainText), txtSub = mkDiv(tBox),
ts = tBox.style, stLen = textWidth(subText, fontF, mSize)+5; ts.color = "#fff";
ts.font = mSize+"pt "+fontF; ts.fontWeight = 100; txtSub.style.fontWeight = 400;
//Generate subtext SVG for knockout effect:
txtSub.innerHTML =
"<svg xmlns='http://www.w3.org/2000/svg' width='"+stLen+"px' height='"+(mSize+11)+"px' viewBox='0 0 "+stLen+" "+(mSize+11)+"'>"+
"<rect x='0' y='0' width='100%' height='100%' fill='#fff' rx='4px' ry='4px' mask='url(#txtSubMask)'></rect>"+
"<mask id='txtSubMask'>"+
"<rect x='0' y='0' width='100%' height='100%' fill='#fff'></rect>"+
"<text x='"+(stLen/2)+"' y='"+(mSize+6)+"' font='"+mSize+"pt "+fontF+"' text-anchor='middle' fill='#000'>"+subText+"</text>"+
"</mask>"+
"</svg>";
//Relevant Helper Functions:
function centeredDiv(parent) {
//Container:
var d = document.createElement('div'), s = d.style;
s.display = "table"; s.position = "relative"; s.zIndex = 999;
s.top = s.left = 0; s.width = s.height = "100%";
//Content Box:
var k = document.createElement('div'), j = k.style;
j.display = "table-cell"; j.verticalAlign = "middle";
j.textAlign = "center"; d.appendChild(k);
parent.appendChild(d); return k;
}
function mkDiv(parent, tCont) {
var d = document.createElement('div');
if(tCont) d.textContent = tCont;
parent.appendChild(d); return d;
}
function textWidth(text, font, size) {
var canvas = window.textWidthCanvas || (window.textWidthCanvas = document.createElement("canvas")),
context = canvas.getContext("2d"); context.font = size+(typeof size=="string"?" ":"pt ")+font;
return context.measureText(text).width;
}
Just throw that in your window.onload, set the body's background to your image, and watch the magic happen!
mix-blend-mode is also a possibility for that kind of effect .
The mix-blend-mode CSS property sets how an element's content should blend with the content of the element's parent and the element's background.
h1 {
background:white;
mix-blend-mode:screen;
/* demo purpose from here */
padding:0.25em;
mix-blend-mode:screen;
}
html {
background:url(https://i.picsum.photos/id/1069/367/267.jpg?hmac=w5sk7UQ6HGlaOVQ494mSfIe902cxlel1BfGUBpEYoRw)center / cover ;
min-height:100vh;
display:flex;
}
body {margin:auto;}
h1:hover {border:dashed 10px white;background-clip:content-box;box-shadow:inset 0 0 0 2px #fff, 0 0 0 2px #fff}
<h1>ABCDEFGHIJKLMNOPQRSTUVWXYZ</h1>
This worked for me mix-blend-mode: color-dodge on the container with opposite colors.
.main{
background: url('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg');
height: 80vh;
width: 100vw;
padding: 40px;
}
.container{
background-color: white;
width: 80%;
height: 50px;
padding: 40px;
font-size: 3em;
font-weight: 600;
mix-blend-mode: color-dodge;
}
.container span{
color: black;
}
<div class="main">
<div class="container">
<span>This is my text</span>
</div>
</div>
Not possible with CSS just now I'm afraid.
Your best bet is to simply use an image (probably a PNG) and and place good alt/title text on it.
Alternatively you could use a SPAN or a DIV and have the image as a background to that with your text you want for SEO purposes inside it but text-indent it off screen.

crop GIF images without loosing animation using javascript [duplicate]

I want to show an image from an URL with a certain width and height even if it has a different size ratio.
So I want to resize (maintaining the ratio) and then cut the image to the size I want.
I can resize with html img property and I can cut with background-image.
How can I do both?
Example:
This image:
Has the size 800x600 pixels and I want to show like an image of 200x100 pixels
With img I can resize the image 200x150px:
<img
style="width: 200px; height: 150px;"
src="http://i.stack.imgur.com/wPh0S.jpg">
That gives me this:
<img style="width: 200px; height: 150px;" src="https://i.stack.imgur.com/wPh0S.jpg">
And with background-image I can cut the image 200x100 pixels.
<div
style="background-image:
url('https://i.stack.imgur.com/wPh0S.jpg');
width:200px;
height:100px;
background-position:center;"> </div>
Gives me:
<div style="background-image:url('https://i.stack.imgur.com/wPh0S.jpg'); width:200px; height:100px; background-position:center;"> </div>
How can I do both?
Resize the image and then cut it the size I want?
You could use a combination of both methods eg.
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 400px;
height: 300px;
margin: -75px 0 0 -100px;
}
<div class="crop">
<img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">
</div>
You can use negative margin to move the image around within the <div/>.
With CSS3 it's possible to change the size of a background-image with background-size, fulfilling both goals at once.
There are a bunch of examples on css3.info.
Implemented based on your example, using donald_duck_4.jpg. In this case, background-size: cover; is just what you want - it fits the background-image to cover the entire area of the containing <div> and clips the excess (depending on the ratio).
.with-bg-size {
background-image: url('https://i.stack.imgur.com/wPh0S.jpg');
width: 200px;
height: 100px;
background-position: center;
/* Make the background image cover the area of the <div>, and clip the excess */
background-size: cover;
}
<div class="with-bg-size">Donald Duck!</div>
css3 background-image background-size
Did you try to use this?
.centered-and-cropped { object-fit: cover }
I needed to resize image, center (both vertically and horizontally) and than crop it.
I was happy to find, that it could be done in a single css-line.
Check the example here: http://codepen.io/chrisnager/pen/azWWgr/?editors=110
Here is the CSS and HTMLcode from that example:
.centered-and-cropped { object-fit: cover }
<h1>original</h1>
<img height="200" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
<h1>object-fit: cover</h1>
<img class="centered-and-cropped" width="200" height="200"
style="border-radius:50%" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3174/bear.jpg" alt="Bear">
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
img {
position: absolute;
clip: rect(0px, 140px, 140px, 0px);
}
<img src="w3css.gif" width="100" height="140" />
Thanks sanchothefat.
I have an improvement to your answer. As crop is very tailored for every image, this definitions should be at the HTML instead of CSS.
<div style="overflow:hidden;">
<img src="img.jpg" alt="" style="margin:-30% 0px -10% 0px;" />
</div>
object-fit may help you, if you're playing with <img> tag
The below code will crop your image for you. You can play around with object-fit
img {
object-fit: cover;
width: 300px;
height: 337px;
}
A small addition to the previous answers that includes object-fit: cover:
object-position
You can alter the alignment of the replaced element's content object within the element's box using the object-position property.
.trimmed-cover {
object-fit: cover;
width: 100%;
height: 177px;
object-position: center 40%;
}
<img class="trimmed-cover" src="http://i.stack.imgur.com/wPh0S.jpg">
img {
position: absolute;
clip: rect(0px,60px,200px,0px);
}
Try using the clip-path property:
The clip-path property lets you clip an element to a basic shape or to
an SVG source.
Note: The clip-path property will replace the deprecated clip
property.
img {
width: 150px;
clip-path: inset(30px 35px);
}
<img src="http://i.stack.imgur.com/wPh0S.jpg">
More examples here.
Live Example:
https://jsfiddle.net/de4Lt57z/
HTML:
<div class="crop">
<img src="example.jpg" alt="..." />
</div>
CSS:
.crop img{
width:400px;
height:300px;
position: absolute;
clip: rect(0px,200px, 150px, 0px);
}
Explanation:
Here image is resized by width and height value of the image. And crop is done by clip property.
For details about clip property follow:
http://tympanus.net/codrops/2013/01/16/understanding-the-css-clip-property/
In the crop class, place the image size that you want to appear:
.crop {
width: 282px;
height: 282px;
overflow: hidden;
}
.crop span.img {
background-position: center;
background-size: cover;
height: 282px;
display: block;
}
The html will look like:
<div class="crop">
<span class="img" style="background-image:url('http://url.to.image/image.jpg');"></span>
</div>
<p class="crop"><a href="http://templatica.com" title="Css Templates">
<img src="img.jpg" alt="css template" /></a></p>
.crop {
float: left;
margin: .5em 10px .5em 0;
overflow: hidden; /* this is important */
position: relative; /* this is important too */
border: 1px solid #ccc;
width: 150px;
height: 90px;
}
.crop img {
position: absolute;
top: -20px;
left: -55px;
}
There are services like Filestack that will do this for you.
They take your image url and allow you to resize it using url parameters. It is pretty easy.
Your image would look like this after resizing to 200x100 but keeping the aspect ratio
The whole url looks like this
https://process.filestackapi.com/AhTgLagciQByzXpFGRI0Az/resize=width:200/crop=d:[0,25,200,100]/https://i.stack.imgur.com/wPh0S.jpg
but the important part is just
resize=width:200/crop=d:[0,25,200,100]
You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.
What I've done is to create a server side script that will resize and crop a picture on the server end so it'll send less data across the interweb.
It's fairly trivial, but if anyone is interested, I can dig up and post the code (asp.net)
<div class="crop">
<img src="image.jpg"/>
</div>
.crop {
width: 200px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 100%;
/*Here you can use margins for accurate positioning of cropped image*/
}
If you are using Bootstrap, try using { background-size: cover;
} for the <div> maybe give the div a class say <div class="example" style=url('../your_image.jpeg');> so it becomes
div.example{
background-size: cover}
I needed to do this recently. I wanted to make a thumbnail-link to a NOAA graph. Since their graph could change at any time, I wanted my thumbnail to change with it. But there's a problem with their graph: it has a huge white border at the top, so if you just scale it to make the thumbnail you end up with extraneous whitespace in the document.
Here's how I solved it:
http://sealevel.info/example_css_scale_and_crop.html
First I needed to do a little bit of arithmetic. The original image from NOAA is 960 × 720 pixels, but the top seventy pixels are a superfluous white border area. I needed a 348 × 172 thumbnail, without the extra border area at the top. That means the desired part of the original image is 720 - 70 = 650 pixels high. I needed to scale that down to 172 pixels, i.e., 172 / 650 = 26.5%. That meant 26.5% of 70 = 19 rows of pixels needed to be deleted from the top of the scaled image.
So…
Set the height = 172 + 19 = 191 pixels:
height=191
Set the bottom margin to -19 pixels (shortening the image to 172 pixels high):
margin-bottom:-19px
Set the top position to -19 pixels (shifting the image up, so that the top 19 pixel rows overflow & are hidden instead of the bottom ones):
top:-19px
The resulting HTML looks like this:
<a href="…" style="display:inline-block;overflow:hidden">
<img width=348 height=191 alt=""
style="border:0;position:relative;margin-bottom:-19px;top:-19px"
src="…"></a>
As you can see, I chose to style the containing <a> tag, but you could style a <div>, instead.
One artifact of this approach is that if you show the borders, the top border will be missing. Since I use border=0 anyhow, that wasn't an issue for me.
You can use Kodem's Image Resize Service. You can resize any image with just a http call. Can be used casually in the browser or used in your production app.
Upload the image somewhere you prefer (S3, imgur etc.)
Plug it into your dedicated API url (from our dashboard)
You can also use a tool called Croppie that can crop images...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="https://foliotek.github.io/Croppie/croppie.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script>
<script src="https://foliotek.github.io/Croppie/croppie.js"> </script>
<script src="https://foliotek.github.io/Croppie/bower_components/exif-js/exif.js"> </script>
<style>
#page {
background: #ffffff;
padding: 20px;
margin: 20px;
}
#demo-basic {
width: 600px;
height: 600px;
}
</style>
</head>
<body>
<h1>Crop Image Demo</h1>
<input id="upload" type="file" />
<br />
<div id="page">
<div id="demo-basic"></div>
</div>
<input id="upload-result" type="button" value="Crop Image"/>
<br />
<img id="cropped-result" src=""/>
<script>
var $uploadCrop;
$("#upload").on("change", function () { readFile(this); show(); });
$("#upload-result").on("click", function (ev) {
$uploadCrop.croppie("result", {
type: "canvas",
size: "viewport"
}).then(function (resp) {
$("#cropped-result").attr("src", resp);
});
});
function show() {
$uploadCrop = $("#demo-basic").croppie({
viewport: { width: 100, height: 100 },
boundary: { width: 300, height: 300 },
enableResize: true,
enableOrientation: true,
mouseWheelZoom: 'ctrl',
enableExif: true
});
}
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#demo-basic").addClass("ready");
$uploadCrop.croppie("bind", {
url: e.target.result
}).then(function () {
console.log("jQuery bind complete");
});
}
reader.readAsDataURL(input.files[0]);
}
else {
alert("Sorry - you're browser doesn't support the FileReader API");
}
}
</script>
</body>
</html>

Is there a way to auto add gradient to images?

Here is my code:
<div class='my-posts-container' id='<%=postobj._id%>'>
<%var menuid='menu'+postobj._id%>
<%var imagesource='../'+postobj.blob.path%>
<div class="my-posts-container-header">
<%-include('postheader.ejs',{friend:postobj.username,postid:postobj._id});%>
</div>
<div class="menu hide" id="<%=menuid%>" >
<ul >
<li><button onclick="viewpost('<%=postobj._id%>')" >view</button></li>
<li><button onclick="removepost('<%=postobj._id%>')" >remove</button></li>
<!-- <li><button onclick="copypostlink('<%=postobj._id%>')" >copy link</button></li>
<li><button onclick="editthispost('<%=postobj._id%>')" >edit</button></li> -->
</ul>
</div>
<div class="post-image" >
<img src="<%=imagesource%>" alt="image" height="400px" width="400px" style="margin: 5px;object-fit: contain;" ondblclick="like('<%=postobj._id%>')">
</div>
<span>
<%-include('likecommentsharesave.ejs',{postid:postobj._id,username:username,likes:postobj.likes})%>
</span>
<hr>
<div class="caption">
<%=postobj.caption%>
</div>
I want to keep my image size as 400px *400px
but add a background colour .post_image div,
basically, I want to add a gradient to the background based on any image in the image tag, something like this,
so that the whole 400 X 400 size is covered is this possible to achieve, if not can you suggest me other options, Thanks.
You can achieve something similar with CSS
Considering using this stylesheet
<style type="text/css">
.blured {
width:320px;
height:320px;
position: relative;
overflow: hidden;
}
.blured .blur {
height:70px;
width:100%;
position:absolute;
filter: blur(7px);
}
.blured .top {
top:0px;
background: linear-gradient(#000000d9, #00000000)
}
.blured .bottom {
bottom:0px;
background: linear-gradient(#00000000, #000000d9)
}
</style>
Then use the following markup
<div class='blured' style='background-image:url("http://placekitten.com/320/320")'>
<div class='blur top'></div>
<div class='blur bottom'></div>
</div>
The result will be something like this:
You can experiment with linear-gradient colors and the value for blur() to achieve an output close to your requirement.
References:
filter:blur()
background: linear-gradient
The effect you describe can actually be achieved. You just need to stack the same image with a smaller size on top of the image. The image underneath can then be blurred out and it will span the remainder of the 400px x 400px area.
To do this, you need to set the position field of the enclosing div to relative and that of both the images to absolute. I have reduced the height of the image sitting on top to 200px and kept the image width the same as the image underneath to resemble the style of the image in the question. Use filter: blur() to blur out the larger image.
Blurring softens the edges of the image (Remove the clip property and you'll know). Use the clip property to make the edges look "crisp".
I have used this image.
Run the code snippet below to see it in action:
<!DOCTYPE html>
<html>
<style>
*{box-sizing: border-box;}
.container {
margin: auto;
position: relative;
width: 50%;
}
.outer {
filter: blur(5px);
position: absolute;
z-index: -1;
clip: rect(0,400px,400px,0);
}
.inner {
position: absolute;
top: 100px;
}
</style>
<div class="container">
<img src="https://i.stack.imgur.com/Y1ELT.jpg" class="outer" height="400px" width="400px">
<img src="https://i.stack.imgur.com/Y1ELT.jpg" class="inner" height="200px" width="400px">
</div>
</html>
This answers part of your question. Now, to automate the image placement as per size, you can retrieve and update the image dimensions using JavaScript:
var image = new Image();
image.onload = function() {
var height = image.height;
var width = image.width;
}
image.src = "<source>";
The image underneath will always be 400 x 400 px, you can update the attributes of the image on the top as per its actual retrieved dimensions if it is smaller than 400 x 400 px. Otherwise, squash it down to 400 x 400 px to cover the entire image underneath.

getBoundingClientRect within svg incorrect only on Chrome

When calling getBoundingClientRect of a div within an svg in order to position other elements outside of the svg accordingly, the top and left values are too high only on Chrome (78.0.3904.108) and Windows 10.
Here is a codepen to demonstrate the problem. The red border around the green box is positioned using the getBoundingClientRect coordinates of the element within the svg. On Windows Chrome, you'll see the result of the top and left values being inflated somehow (first screenshot below). In other browsers it behaves as expected (second screenshot). Is there a better way to achieve this, or is there a reason for why this issue only appears in Windows Chrome?
Update: Adding code snippet.
const svg = document.querySelector('.svg');
const ref = document.querySelector('.ref');
const outer = document.querySelector('.outer');
const refRect = ref.getBoundingClientRect();
console.log('.svg BoundingClientRect', svg.getBoundingClientRect());
console.log('.ref BoundingClientRect', refRect);
$(outer).css('top', refRect.top - window.scrollY)
$(outer).css('left', refRect.left - window.scrollX)
svg {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
}
.ref {
background: #ccffcc;
width: 100%;
height: 100%;
}
.outer {
border: 1px solid red;
width: 100px;
height: 100px;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="svg" version="1.1" xmlns="http://www.w3.org/2000/svg">
<foreignObject x="18%" y="14%" width="100" height="100">
<div class="ref">This should be perfectly surrounded by a red border</div>
</foreignObject>
</svg>
<div class="outer"></div>

is it possible make a text color to inherit a its parent background color? [duplicate]

Is there any way to make a transparent text cut out of a background effect like the one in the following image, with CSS?
It would be sad to lose all precious SEO because of images replacing text.
I first thought of shadows but I can't figure anything out...
The image is the site background, an absolute positioned <img> tag
It's possible with css3 but it's not supported in all browsers
With background-clip: text; you can use a background for the text, but you will have to align it with the background of the page
body {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
margin:10px;
}
h1 {
background-color:#fff;
overflow:hidden;
display:inline-block;
padding:10px;
font-weight:bold;
font-family:arial;
color:transparent;
font-size:200px;
}
span {
background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
display:block;
}
<h1><span>ABCDEFGHIKJ</span></h1>
http://jsfiddle.net/JGPuZ/1337/
Automatic Alignment
With a little javascript you can align the background automatically:
$(document).ready(function(){
//Position of the header in the webpage
var position = $("h1").position();
var padding = 10; //Padding set to the header
var left = position.left + padding;
var top = position.top + padding;
$("h1").find("span").css("background-position","-"+left+"px -"+top+"px");
});
body {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
margin:10px;
}
h1 {
background-color:#fff;
overflow:hidden;
display:inline-block;
padding:10px;
font-weight:bold;
font-family:arial;
color:transparent;
font-size:200px;
}
span {
background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span>ABCDEFGHIKJ</span></h1>
​
http://jsfiddle.net/JGPuZ/1336/
Although this is possible with CSS, a better approach would be to use an inline SVG with SVG masking. This approach has some advantages over CSS :
Much better browser support: IE10+, chrome, Firefox, safari...
This doesn't impact SEO as spiders can crawl SVG content (google indexes SVG content since 2010)
CodePen Demo : SVG text mask
body,html{height:100%;margin:0;padding:0;}
body{
background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
background-size:cover;
background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
<defs>
<mask id="mask" x="0" y="0" width="100" height="50">
<rect x="0" y="0" width="100" height="40" fill="#fff"/>
<text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
<text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
</mask>
</defs>
<rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>
</svg>
If you aim on making the text selectable and searchable, you need to include it outside the <defs> tag. The following example shows a way to do that keeping the transparent text with the <use> tag:
body,html{height:100%;margin:0;padding:0;}
body{
background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
background-size:cover;
background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
<defs>
<g id="text">
<text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
<text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
</g>
<mask id="mask" x="0" y="0" width="100" height="50">
<rect x="0" y="0" width="100" height="40" fill="#fff"/>
<use xlink:href="#text" />
</mask>
</defs>
<rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>
<use xlink:href="#text" mask="url(#mask)" />
</svg>
There is a simple way to do this with just CSS:
background: black;
color: white;
mix-blend-mode: multiply;
for transparent text on a black background, or
background: white;
color: black;
mix-blend-mode: screen;
for transparent text on a white background.
Put these styles on your text element with whichever background you want behind it.
Example CodePen
Read up on mix-blend-mode and experiment with it to use different colours.
Caveats:
For this to work in chrome, you also need to explicitly set a background colour on the html element.
This works on basically all modern browsers except IE.
It is possible, but so far only with Webkit based browsers (Chrome, Safari, Rockmelt, anything based on the Chromium project.)
The trick is to have an element within the white one that has the same background as the body, then use -webkit- background-clip: text; on the inner element which basically means "don't extend the background beyond the text" and use transparent text.
section
{
background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
width: 100%;
height: 300px;
}
div
{
background: rgba(255, 255, 255, 1);
color: rgba(255, 255, 255, 0);
width: 60%;
heighT: 80%;
margin: 0 auto;
font-size: 60px;
text-align: center;
}
p
{
background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
-webkit-background-clip: text;
}
​
http://jsfiddle.net/BWRsA/
just put that css
.banner-sale-1 .title-box .title-overlay {
font-weight: 900;
overflow: hidden;
margin: 0;
padding-right: 10%;
padding-left: 10%;
text-transform: uppercase;
color: #080404;
background-color: rgba(255, 255, 255, .85);
/* that css is the main think (mix-blend-mode: lighten;)*/
mix-blend-mode: lighten;
}
I just discovered a new way to do this while messing around, I'm not entirely sure how it works ( if someone else wants to explain please do ).
It seems to work very well, and requires no double backgrounds or JavaScript.
Here's the code:
JSFIDDLE
body {
padding: 0;
margin: 0;
}
div {
background: url(http://www.color-hex.com/palettes/26323.png) repeat;
width: 100vw;
height: 100vh;
}
body::before {
content: '$ALPHABET';
left: 0;
top: 0;
position: absolute;
color: #222;
background-color: #fff;
padding: 1rem;
font-family: Arial;
z-index: 1;
mix-blend-mode: screen;
font-weight: 800;
font-size: 3rem;
letter-spacing: 1rem;
}
<div></div>
In the near future we can use element() to achieve this
The element() function allows an author to use an element in the document as an image. As the referenced element changes appearance, the image changes as well ref
The trick is to create a common div with text then use element() combined with mask.
Here is a basic example that works only on the latest version Firefox for now.
#text {
font-size:35px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
background:red;
-webkit-mask:
-moz-element(#text) center/contain no-repeat, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
}
<div id="text">
You can put your text here
</div>
<div class="main">
</div>
It will produce the following:
It's reponsive since we rely on basic background properties and we can easily update the text using basic CSS.
We can consider any kind of content and also create patterns:
#text {
font-size:30px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
padding:20px;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
#text span {
font-family:cursive;
font-size:35px;
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
background:red;
-webkit-mask:
-moz-element(#text) 0 0/20% auto, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
}
<div id="text">
Your <span>text</span> here 👍
</div>
<div class="main">
</div>
And why not some animation to create an infinite scrolling text:
#text {
font-size:30px;
font-weight:bold;
color:#000;
font-family:sans-serif;
text-transform: uppercase;
white-space:nowrap;
padding:20px 5px;
/* we hide it */
position:fixed;
right:200vw;
bottom:200vh
}
body {
background:url(https://picsum.photos/id/1018/800/800) center/cover;
}
.main {
margin:50px;
height:100px;
padding-right:calc(50% - 50px);
background:red;
-webkit-mask:
-moz-element(#text) 0 50%/200% auto content-box, /* this behave like a background-image*/
linear-gradient(#fff 0 0);
mask-composite:exclude;
animation:m 5s linear infinite;
}
#keyframes m{
to {-webkit-mask-position:200% 50%}
}
<div id="text">
Srolling repeating text here
</div>
<div class="main">
</div>
I guess you could achieve something like that using background-clip, but I haven't tested that yet.
See this example:
http://www.css3.info/wp-content/uploads/2008/03/webkit-backgroundcliptext_color.html
(Webkit only, I don't know yet how to change the black background to a white one)
You can use an inverted / negative / reverse font and apply it with the font-face="…" CSS rule. You might have to play with letter spacing to avoid small white gaps between letters.
If you do not require a specific font, it's simple. Download a likeable one, for example from this collection of inverted fonts.
If you require a specific font (say, "Open Sans"), it's difficult. You have to convert your existing font into an inverted version. This is possible manually with Font Creator, FontForge etc., but of course we want an automated solution. I could not find instructions for that yet, but some hints:
How to convert a bitmap font into a TrueType font (plus yet another way to do that). One would first use ImageMagick commands to render the font glyphs into high-resolution raster images and to invert them, then convert them back to a TrueType font with the above instructions.
Is it possible to invert a font with FontForge or another PGM?
Creating a reverse (white on black) font
You can use myadzel's Patternizer jQuery plugin to achieve this effect across browsers. At this time, there is no cross-browser way to do this with just CSS.
You use Patternizer by adding class="background-clip" to HTML elements where you want the text to be painted as an image pattern, and specify the image in an additional data-pattern="…" attribute. See the source of the demo. Patternizer will create an SVG image with pattern-filled text and underlay it to the transparently rendered HTML element.
If, as in the question's example image, the text fill pattern should be a part of a background image extending beyond the "patternized" element, I see two options (untested, my favourite first):
Use masking instead of a background image in the SVG. As in web-tiki's answer, to which using Patternizer will still add automatic generation of the SVG and an invisible HTML element on top that allows text selection and copying.
Or use automatic alignment of the pattern image. Can be done with JavaScript code similar to the one in Gijs's answer.
I needed to make text that looked exactly like it does in the original post, but I couldn't just fake it by lining up backgrounds, because there's some animation behind the element. Nobody seems to have suggested this yet, so here's what I did: (Tried to make it as easy to read as possible.)
var el = document.body; //Parent Element. Text is centered inside.
var mainText = "THIS IS THE FIRST LINE"; //Header Text.
var subText = "THIS TEXT HAS A KNOCKOUT EFFECT"; //Knockout Text.
var fontF = "Roboto, Arial"; //Font to use.
var mSize = 42; //Text size.
//Centered text display:
var tBox = centeredDiv(el), txtMain = mkDiv(tBox, mainText), txtSub = mkDiv(tBox),
ts = tBox.style, stLen = textWidth(subText, fontF, mSize)+5; ts.color = "#fff";
ts.font = mSize+"pt "+fontF; ts.fontWeight = 100; txtSub.style.fontWeight = 400;
//Generate subtext SVG for knockout effect:
txtSub.innerHTML =
"<svg xmlns='http://www.w3.org/2000/svg' width='"+stLen+"px' height='"+(mSize+11)+"px' viewBox='0 0 "+stLen+" "+(mSize+11)+"'>"+
"<rect x='0' y='0' width='100%' height='100%' fill='#fff' rx='4px' ry='4px' mask='url(#txtSubMask)'></rect>"+
"<mask id='txtSubMask'>"+
"<rect x='0' y='0' width='100%' height='100%' fill='#fff'></rect>"+
"<text x='"+(stLen/2)+"' y='"+(mSize+6)+"' font='"+mSize+"pt "+fontF+"' text-anchor='middle' fill='#000'>"+subText+"</text>"+
"</mask>"+
"</svg>";
//Relevant Helper Functions:
function centeredDiv(parent) {
//Container:
var d = document.createElement('div'), s = d.style;
s.display = "table"; s.position = "relative"; s.zIndex = 999;
s.top = s.left = 0; s.width = s.height = "100%";
//Content Box:
var k = document.createElement('div'), j = k.style;
j.display = "table-cell"; j.verticalAlign = "middle";
j.textAlign = "center"; d.appendChild(k);
parent.appendChild(d); return k;
}
function mkDiv(parent, tCont) {
var d = document.createElement('div');
if(tCont) d.textContent = tCont;
parent.appendChild(d); return d;
}
function textWidth(text, font, size) {
var canvas = window.textWidthCanvas || (window.textWidthCanvas = document.createElement("canvas")),
context = canvas.getContext("2d"); context.font = size+(typeof size=="string"?" ":"pt ")+font;
return context.measureText(text).width;
}
Just throw that in your window.onload, set the body's background to your image, and watch the magic happen!
mix-blend-mode is also a possibility for that kind of effect .
The mix-blend-mode CSS property sets how an element's content should blend with the content of the element's parent and the element's background.
h1 {
background:white;
mix-blend-mode:screen;
/* demo purpose from here */
padding:0.25em;
mix-blend-mode:screen;
}
html {
background:url(https://i.picsum.photos/id/1069/367/267.jpg?hmac=w5sk7UQ6HGlaOVQ494mSfIe902cxlel1BfGUBpEYoRw)center / cover ;
min-height:100vh;
display:flex;
}
body {margin:auto;}
h1:hover {border:dashed 10px white;background-clip:content-box;box-shadow:inset 0 0 0 2px #fff, 0 0 0 2px #fff}
<h1>ABCDEFGHIJKLMNOPQRSTUVWXYZ</h1>
This worked for me mix-blend-mode: color-dodge on the container with opposite colors.
.main{
background: url('https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg');
height: 80vh;
width: 100vw;
padding: 40px;
}
.container{
background-color: white;
width: 80%;
height: 50px;
padding: 40px;
font-size: 3em;
font-weight: 600;
mix-blend-mode: color-dodge;
}
.container span{
color: black;
}
<div class="main">
<div class="container">
<span>This is my text</span>
</div>
</div>
Not possible with CSS just now I'm afraid.
Your best bet is to simply use an image (probably a PNG) and and place good alt/title text on it.
Alternatively you could use a SPAN or a DIV and have the image as a background to that with your text you want for SEO purposes inside it but text-indent it off screen.

Categories