Skip to content

Commit

Permalink
update placeholder.js
Browse files Browse the repository at this point in the history
  • Loading branch information
hustcc committed Jun 13, 2016
1 parent a0543f7 commit aabf320
Show file tree
Hide file tree
Showing 16 changed files with 316 additions and 179 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
node_modules
2 changes: 1 addition & 1 deletion .travis.yml
@@ -1,3 +1,3 @@
language: node_js
node_js:
- 0.6
- 4.4.4
18 changes: 7 additions & 11 deletions README-zh.md
Expand Up @@ -16,7 +16,7 @@
## 二、特点

1. 不依赖任何 js 框架,比如 jq
2. YUI压缩大小1.65kb,gzip之后为`941 b`,小于1k
2. YUI压缩大小1.46kb,gzip之后为`851 b`,小于1k
3. 配置项多,都有默认值
4. 使用简单

Expand All @@ -30,15 +30,15 @@
引入 placeholder.js 到你的前端代码中:

```html
<script src="placeholder.js"></script>
<script src="dist/placeholder.min.js"></script>
```

提供免费CDN:

1. [bootcdn placeholder.js](http://www.bootcdn.cn/placeholder.js/)
2. [cndjs placeholder.js](https://cdnjs.com/libraries/placeholder.js)

### 3.2 通过 ES6引入
### 3.2 通过 ES6 引入

```js
// install before
Expand Down Expand Up @@ -125,6 +125,7 @@ size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&

* `placeholder.getData(opts)`: 获得placeholder图片的base64字符串,可以直接在img标签的src属性中使用,或者在css的背景中使用。
* `placeholder.getCanvas(opts)`: 获得canvas元素, 可以直接插入到DOM结构中。
* `placeholder.render()`: 渲染**class='placeholder'**的img标签,并且使用对应的options作为渲染参数。


## 六、为什么要造轮子
Expand All @@ -133,13 +134,8 @@ size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&
2. [imsky/holder]( https://github.com/imsky/holder)是客户端生成,大名鼎鼎,但是在用到网页上,动态图片的时候,它的那种风格用起来不太方便。
3. 其他的 image placeholder 太大了,比如上面提到的 holder 压缩之后还有 30k 以上,其实`不太使用在网页上使用`

## 八、LICENSE

## 七、待完成
MIT

1. 更多的灵活配置。
2. 作为浏览器端的js库,尽可能的压缩大小。


## 八、其他

任何问题欢迎反馈和 pr ,代码非常简单,相信 1 分钟你就可以看懂,非常欢迎`push request`
[关于项目的 react 版本, 可以看 react-placeholder.](http://github.com/hustcc/react-placeholder)
20 changes: 8 additions & 12 deletions README.md
Expand Up @@ -16,8 +16,8 @@ A javascript library to generate `placeholder image` on client browser side. [
## 2. Feature

- Pure javascript, do not depends on jQuery or other javascript framework.
- Very lite, only 1.65kb. and `941 b` after gzip.
- So many option config, all has default value.
- Very lite, only 1.46kb. and `851 b` after gzip.
- Many options config, all has default value.
- Very easy to use.


Expand All @@ -30,7 +30,7 @@ Two method to import into you page.
Include placeholder.js in your HTML:

```html
<script src="placeholder.js"></script>
<script src="dist/placeholder.min.js"></script>
```

CDN is supported at:
Expand All @@ -53,7 +53,7 @@ var placeholder = require("placeholder.js");

UMD import is supported, then get global object: `placeholder`.

### 3.3 What's the method
### 3.3 How to use

`1.` Programmatic use API to process image with a specific src attribute, like this one:

Expand Down Expand Up @@ -125,6 +125,7 @@ size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&

* `placeholder.getData(opts)`: Get the base64 string of placeholder image, can be used in the `src` of img, or in the background-url of css style.
* `placeholder.getCanvas(opts)`: Get the canvas element, can be append to DOM.
* `placeholder.render(force)`: Render the `img` tags which with **class='placeholder'**. and with the tag attribute `options`. `force` is true, will render all the node again, else, will only render img which has not been rendered. default is `false`.


## 6. Why another Holder?
Expand All @@ -133,13 +134,8 @@ size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&
- [imsky/holder](https://github.com/imsky/holder) can generate on client browser side, `BUT`, the sytle is `holder.js/300x200`, so hard to use on website when need dynamic image.
- Other image placeholder javascript file size is too large, such as `imsky/holder is 30.8 KB`, not suitable for website.

## 7. LICENSE

## 7. TODO
MIT

1. More useful option paramters.
2. As a client javascript library, try more and more smaller.


## 8. Other

welcome pr and issue, the code is simple.
[for react version, see react-placeholder.](http://github.com/hustcc/react-placeholder)
133 changes: 133 additions & 0 deletions dist/placeholder.js
@@ -0,0 +1,133 @@
!function (root, factory) {
if (typeof module === 'object' && module.exports)
module.exports = factory(root);
else
root.placeholder = factory(root);
}(typeof window !== 'undefined' ? window : this, function () {

var c,
cc, //公用一个实例,减少内存占用,减少资源消耗
rendered_attr = 'placeholder-rendered';
function createCanvas(opts) {
if (!c || !cc) {
//如果不存在则实例化
c = document.createElement('canvas');
cc = c.getContext('2d');
}
var canvas_width = parseInt(opts.a[0]), canvas_height = parseInt(opts.a[1]);
//图片大小
c.width = canvas_width;
c.height = canvas_height;
cc.clearRect(0, 0, canvas_width, canvas_height); //清楚已有的画布
//设置背景色
cc.fillStyle = opts.c;
cc.fillRect(0, 0, canvas_width, canvas_height);
//字体颜色
cc.fillStyle = opts.d;
cc.font = opts.e + ' normal ' + opts.f + ' ' + (opts.g || 100) + 'px ' + opts.h;
var scale = 1.0;
if (opts.g === '') {
//auto calculate size
var width_limit = 0.7 * canvas_width,
heigth_limit = 0.7 * canvas_height,
text_width = cc.measureText(opts.b).width,
text_height = 100;
scale = Math.min(width_limit / text_width, heigth_limit / text_height);
}
//文字居中
cc.translate(canvas_width / 2, canvas_height / 2);
cc.scale(scale, scale);
cc.textAlign = 'center';
cc.textBaseline = 'middle';

cc.fillText(opts.b, 0, 0);
return c;
}

//随机颜色值
function randomColor() {
return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(-6);
}

//预处理配置信息,补全默认项
function prepareOpts(opts) {
opts = opts || {};
var size = opts.size || '128x128',
text = opts.text || size,
bgcolor = opts.bgcolor || randomColor(), //other placeholder default bgcolor is '#ccc',
color = opts.color || randomColor(), //other placeholder default color is '#969696',
//font参数
fstyle = opts.fstyle || 'normal', //normal / italic / oblique
fweight = opts.fweight || 'bold', //normal / bold / bolder / lighter
fsize = opts.fsize || '', //auto calculate the font size to response to the image size
ffamily = opts.ffamily || 'consolas', //规定字号和行高,以像素计。
new_opts = {};

size = size.split('x');
if (size.length !== 2) {
size = [128, 128];
}
//减少键值,压缩之后可以减少包大小
new_opts.a = size;
new_opts.b = text;
new_opts.c = bgcolor;
new_opts.d = color;
new_opts.e = fstyle;
new_opts.f = fweight;
new_opts.g = fsize;
new_opts.h = ffamily;
opts = null;
return new_opts;
}

//创建placeholder Canvas元素
function placeholderCanvas(opts) {
opts = prepareOpts(opts);
return createCanvas(opts);
}

//获得placeholder的base64字符串
function placeholder(opts) {
return placeholderCanvas(opts).toDataURL();
}

//获取元素属性,带默认值
function _getAttribute(node, name, defaultValue) {
return node.getAttribute(name) || defaultValue;
}

//从url中解析配置信息
function parseUrlOptions(url) {
var opts = {}, parameters = url.split('&'), k_v;
for (var i in parameters) {
k_v = parameters[i].split('=');
try {
opts[k_v[0]] = decodeURIComponent(k_v[1]);
} catch (e) {
opts[k_v[0]] = k_v[1];
}
}
return opts;
}
//开始检查图片中
function render(force) {
var image_eles = document.querySelectorAll('img.placeholder'), img, opts;
for (var i = 0; i < image_eles.length; i++) {
img = image_eles[i];
//图片没有被处理过,立马处理
if (force || (! _getAttribute(img, rendered_attr, ''))) {
opts = parseUrlOptions(_getAttribute(img, 'options', ''));
img.setAttribute('src', placeholder(opts));
//处理完成之后标记为处理
img.setAttribute(rendered_attr, '1');
}
}
}
render(); //非force渲染

return {
getData: placeholder,
getCanvas: placeholderCanvas,
render: render
};
});
1 change: 1 addition & 0 deletions dist/placeholder.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion doc/demo.html
Expand Up @@ -12,7 +12,7 @@
</head>

<body>
<script type="text/javascript" src="../placeholder.js"></script>
<script src="../dist/placeholder.min.js"></script>
<div id="container" style="position:float;float:right">
placeholder a qrcode.
<div style="position: relative; left: 0px; top: 0px; padding: 0px; margin: 0px; width: 450px; height: 450px; background-image: rgb(255, 255, 255);">
Expand Down Expand Up @@ -265,6 +265,9 @@

<img options="size=256x128&text=Hello%2525%26%3DWorld" class="placeholder" options="bgcolor=#2b5f07&text=%20&size=19x19">
<pre>&lt;img options="size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&fsize=40&ffamily=consolas" class="placeholder" options="bgcolor=#2b5f07&text=%20&size=19x19"&gt;</pre>
<script type="text/javascript">
placeholder.render();
</script>
<img options="size=256x128&text=Hello!&bgcolor=#ccc&color=#969696&fstyle=oblique&fweight=bold&fsize=40&ffamily=consolas" class="placeholder" options="bgcolor=#2b5f07&text=%20&size=19x19">
<span style="display:none"><script src="http://s4.cnzz.com/stat.php?id=1257060683&web_id=1257060683" language="JavaScript"></script></span>
</body>
Expand Down
2 changes: 1 addition & 1 deletion doc/index.html
Expand Up @@ -10,7 +10,7 @@
<style type="text/css">
.text{margin:0;padding:5px;border:0;width:70px;height:20px;background:#eee;line-height:20px;outline:0}.picker{margin:0;padding:5px;border:0;width:70px;height:20px;border-right:30px solid green;background:#eee;line-height:20px;outline:0}#placeholder-demo,#placeholder-generator{padding:5% 10%}#placeholder-generator img{margin:0 auto;display:block;max-width:100%}.input-box{float:left;margin-left:15px;margin-right:15px}.input-placeholder{display:block;font-size:24px;color:#666}#select-fstyle{width:100px;height:30px;color:#999}#select-fstyle option{color:#999;background:#eee;border:0}.open-select{background:#ccc;width:30px;height:30px;position:relative;border:0;outline:0;float:right}.options{position:absolute;left:-80px;right:0;top:30px;color:#999;background:#f5f5f5;display:none;text-align:left}.options li{padding:5px 10px}.options li:hover{background:#1e90ff;color:#fff;cursor:pointer}.options li{border-bottom:1px solid #eee}.triangle-down{position:absolute;width:0;height:0;border-left:3px solid transparent;border-right:3px solid transparent;border-top:6px solid #000;top:12px;left:12px}#text{width:300px}
</style>
<script type="text/javascript" src="../placeholder.js"></script>
<script src="../dist/placeholder.min.js"></script>

<!--颜色选择-->
<script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
Expand Down
15 changes: 15 additions & 0 deletions gulpfile.js
@@ -0,0 +1,15 @@
const fs = require('fs');
const gulp = require('gulp');
const wrap = require('gulp-wrap');
const uglify = require('gulp-uglify');
const rename = require("gulp-rename");

gulp.task('mini', () => (
gulp.src('src/src.js')
.pipe(wrap({src: 'src/exports.js'}))
.pipe(rename("placeholder.js"))
.pipe(gulp.dest('dist/'))
.pipe(uglify()) //uglify
.pipe(rename("placeholder.min.js"))
.pipe(gulp.dest('dist/'))
));

0 comments on commit aabf320

Please sign in to comment.