Table of Contents
实现类似Pinterest 的图片预加载功能
Home Web Front-end JS Tutorial JavaScript imitates Pinterest to implement image preloading function

JavaScript imitates Pinterest to implement image preloading function

Dec 09, 2016 am 10:18 AM
javascript

前言

对于Pinterest网站,从前端设计出发的话,我们一定不会忘记我们曾经非常流行的瀑布流布局。但是今天,给大家简要分析下 Pinterest上另外一项非常值得借鉴图片加载细节。

看看下面的截图:

JavaScript imitates Pinterest to implement image preloading function

大家可以感觉到图片出来的时候预先绘制轮廓,重点是预制区域的颜色采用与图片较为相似的色彩值,当图片加载完全后,会有种渐入的效果。

其中谷歌的图片搜索也用到了类似效果:

JavaScript imitates Pinterest to implement image preloading function

我们称之为这种效果为Color Placeholder [色彩预置],当图片加载的时候,我们优先显示其所在容器的背景颜色(如同很多会显示一个加载的gif),由于受限于不同的图片和大小,因此相比与齐刷刷的加载gif,不同色块体验 可能 更好吧(至少Pinterest Google这么认为吧).

实现步骤

接下来我们进入正题,如何自己实现这样的动画加载效果(实现的方式肯定有很多的也欢迎大家提出更好的思路)

我们先定义下基本的html结构

<!--一个post当作一个单位-->
<div class="post">
 <div class="image-bg" style="background-color:#141646">
 <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/89388038777855.Y3JvcCwxMDk1LDg1NiwyNTIsMjE.png"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
 </div>
 <p class="title">Mars</p>
</div>
Copy after login

再看下css设置

.image-bg{
 background: #e1e1e1;
 }
 img {
 width:100%;
 opacity: 0;
 transition: opacity .2s ease-in .25s;
 
 }
 .loaded img {
 opacity: 1;
 }
Copy after login

图片默认是透明度为0,当加载完成后设置为1就行啦。

$(function() {
$(&#39;.post img&#39;).each(function() {
 var el = this;
 var image = new Image();
 image.src = el.src;
 
 image.onload = function() {
  $(el).parent().addClass(&#39;loaded&#39;);
 }
})
 
})
Copy after login

大概基本思路就是这些,但是这里面最核心的就是确定所谓的Dominant Color(图片中主要色彩)。

完整示例如下:

<!doctype html>
<html lang="en">
<head>
<title>实现类似Pinterest 的图片预加载功能</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="//cdn.jsdelivr.net/bootstrap/3.3.6/css/bootstrap.min.css" />
  
<style type="text/css">
  
 html {
 font-family: sans-serif;
 -ms-text-size-adjust: 100%;
 -webkit-text-size-adjust: 100%;
 font-size: 62.5%;
 -webkit-tap-highlight-color: transparent
 }
 
 body {
 font-family: &#39;Helvetica Neue&#39;,&#39;\5FAE\8F6F\96C5\9ED1&#39;,&#39;\9ED1\4F53&#39;,sans-serif;
 letter-spacing: .01rem;
 font-size: 15px;
 line-height: 1.75em;
 color: #3A4145;
 -webkit-font-feature-settings: &#39;kern&#39; 1;
 -moz-font-feature-settings: &#39;kern&#39; 1;
 -o-font-feature-settings: &#39;kern&#39; 1;
  
 }
 h1{
 padding-top: 40px;
 text-align: center;
 }
 .main{
 width: 720px;
 margin: 80px auto;
 text-align: center;
  
 }
 .post{
 margin: 10px;
 font-size: 18px;
 color:#666;
 }
 .title{
 line-height: 30px;
 }
 .image-bg{
 background: #e1e1e1;
 }
 img {
 width:100%;
 opacity: 0;
 transition: opacity .2s ease-in .25s;
  
 }
 .loaded img {
 opacity: 1;
 }
</style>
<script src="//s1.vued.vanthink.cn/jquery-1.10.2.min.js"></script>
</head>
 
<body class="doc">
 <h1 id="实现类似Pinterest-nbsp-的图片预加载功能">实现类似Pinterest 的图片预加载功能</h1>
 <div class="main row">
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#141646">
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/89388038777855.Y3JvcCwxMDk1LDg1NiwyNTIsMjE.png"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
   
  <p class="title">Mars</p>
  </div>
 </div>
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#3e90dc;" >
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/1f430b36513911.Y3JvcCw4MjEsNjQyLDEwMSwzMA.jpg"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
  <p class="title">Grass</p>
  </div>
 </div>
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#09171e;" >
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/4bfb7136056367.Y3JvcCw5NTgsNzQ5LDIyMCwyNg.jpg"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
  <p class="title">journet to the west2</p>
  </div>
 </div>
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#d4cab1;" >
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/96ed6c36255639.Y3JvcCw1NDksNDI5LDEyNiwxODU.png"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
  <p class="title">Marriage</p>
  </div>
 </div>
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#fff8fa;" >
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/ce4a4336970823.Y3JvcCwxMDk1LDg1NiwyNTIsMjE.png"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
  <p class="title">Birthday Card</p>
  </div>
 </div>
 <div class="col-md-6">
  <div class="post">
  <div class="image-bg" style="background-color:#fff;" >
   <img  src="/static/imghw/default1.png"  data-src="https://mir-s3-cdn-cf.behance.net/projects/404/fa5dec36514827.Y3JvcCwxMDk1LDg1Niw0ODUsMTY.png"  class="lazy"     style="max-width:90%"  style="max-width:90%"  / alt="JavaScript imitates Pinterest to implement image preloading function" >
  </div>
  <p class="title">Cup</p>
  </div>
 </div>
  
 </div>
  
<script type="text/javascript">
 $(function() {
 $(&#39;.post img&#39;).each(function() {
  var el = this;
  var image = new Image();
  image.src = el.src;
   
  image.onload = function() {
   $(el).parent().addClass(&#39;loaded&#39;);
  }
 })
  
 })
</script>
</body>
 
</html>
Copy after login

设置背景的颜色

如果你用photoshop打开一张图片的话,你只需要几步就可以确定你希望得到的颜色: 滤镜 -> 模糊 -> 平均即可。

JavaScript imitates Pinterest to implement image preloading function

当然这是针对你所能处理的图片,如果面对海量的图片的话,这个时候我们需要用程序去实现。

寻找到一张图片较为明显的颜色,需要在三维空间中找到一些聚合的点。如果自己写的话,需要去了解一些聚合算法。当然自己并不打算去写更多的内容关于如何去进行图片的这些颜色的生成,这恐怕不是一篇文章能给说完的。实际上你安装ImageMagick就可以简单的实现预期效果:

convert path/or/url/to/image.png -resize 1x1 txt:-
Copy after login

但是这个不太适合我们写程序的。我们可以使用第三方的npm gm

var gm = require(&#39;gm&#39;);
 
gm(&#39;demo1.png&#39;)
 .resize(120, 120)
 .colors(1)
 .toBuffer(&#39;RGB&#39;, function (error, buffer) {
  console.log(buffer.slice(0, 3));
 });
Copy after login

运行输出效果如下:

~ node gm.js
./demo1.png:
<Buffer 34 29 3b>
./demo2.png:
<Buffer cf c3 ad>
Copy after login

对比图如下:

JavaScript imitates Pinterest to implement image preloading function

因此借助程序,我们可以在保存图片的时候进行颜色采集,代码中通过先将图片进行大小调整,实际是出于性能的考虑。有助于节约运算时间。除此之外embed.ly也开放了对应的API,方便你获取网络图片的主要色彩。

如果我们能够有途径获取这样的颜色的话,自然整体功能就没有什么难度了。

扩展

JavaScript imitates Pinterest to implement image preloading function

其实除了纯粹的颜色背景外,我们还可能会遇到类似 medium 的图片(参考上图)预加载技术,才开始图片是模糊的。实际上我们可以通过插件生成一张几素的小图片,然后运用上高四模糊滤镜,然后等待原图加载完毕后,我们在显示原来的图片。

var gm = require(&#39;gm&#39;);
 
gm(&#39;demo1.png&#39;)
 .resize(4, 4)
 .toBuffer(&#39;GIF&#39;, function (error, buffer) {
  console.log(&#39;data:image/gif;base64,&#39; + buffer.toString(&#39;base64&#39;));
 });
Copy after login

<div class="image-bg" style="background-color:#141646">
 <img  src="/static/imghw/default1.png"  data-src="data:image/gif;base64,R0lGODlhBAADAPMJACwlPjAmPDUqOzgrOgQPSgkSShAVRhEWRplcFsR3EAAAAAAAAAAAAAAAAAAAAAAAACH5BAAAAAAALAAAAAAEAAMAAAQJ0"  class="lazy"      style="max-width:90%"  style="max-width:90%" real- / alt="JavaScript imitates Pinterest to implement image preloading function" >
Copy after login

   



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles