From aabf320f2b1890db25bce43497577d01aa548c40 Mon Sep 17 00:00:00 2001 From: hustcc Date: Mon, 13 Jun 2016 13:27:42 +0800 Subject: [PATCH] update placeholder.js --- .gitignore | 1 + .travis.yml | 2 +- README-zh.md | 18 ++---- README.md | 20 +++--- dist/placeholder.js | 133 ++++++++++++++++++++++++++++++++++++++ dist/placeholder.min.js | 1 + doc/demo.html | 5 +- doc/index.html | 2 +- gulpfile.js | 15 +++++ index.html | 2 +- package.json | 14 ++-- placeholder.js | 140 ---------------------------------------- placeholder.min.js | 7 -- src/exports.js | 15 +++++ src/src.js | 119 ++++++++++++++++++++++++++++++++++ test/index.js | 1 - 16 files changed, 316 insertions(+), 179 deletions(-) create mode 100644 .gitignore create mode 100644 dist/placeholder.js create mode 100644 dist/placeholder.min.js create mode 100644 gulpfile.js delete mode 100644 placeholder.js delete mode 100644 placeholder.min.js create mode 100644 src/exports.js create mode 100644 src/src.js delete mode 100644 test/index.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/.travis.yml b/.travis.yml index bced151..43ecc1b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - 0.6 + - 4.4.4 diff --git a/README-zh.md b/README-zh.md index 8802fd1..093282f 100644 --- a/README-zh.md +++ b/README-zh.md @@ -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. 使用简单 @@ -30,7 +30,7 @@ 引入 placeholder.js 到你的前端代码中: ```html - + ``` 提供免费CDN: @@ -38,7 +38,7 @@ 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 @@ -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作为渲染参数。 ## 六、为什么要造轮子 @@ -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`。 \ No newline at end of file +[关于项目的 react 版本, 可以看 react-placeholder.](http://github.com/hustcc/react-placeholder) \ No newline at end of file diff --git a/README.md b/README.md index afc5a21..9ea9978 100644 --- a/README.md +++ b/README.md @@ -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. @@ -30,7 +30,7 @@ Two method to import into you page. Include placeholder.js in your HTML: ```html - + ``` CDN is supported at: @@ -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: @@ -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? @@ -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) diff --git a/dist/placeholder.js b/dist/placeholder.js new file mode 100644 index 0000000..bd0bb30 --- /dev/null +++ b/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 + }; +}); \ No newline at end of file diff --git a/dist/placeholder.min.js b/dist/placeholder.min.js new file mode 100644 index 0000000..b733bcb --- /dev/null +++ b/dist/placeholder.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof module&&module.exports?module.exports=e(t):t.placeholder=e(t)}("undefined"!=typeof window?window:this,function(){function t(t){c&&u||(c=document.createElement("canvas"),u=c.getContext("2d"));var e=parseInt(t.a[0]),n=parseInt(t.a[1]);c.width=e,c.height=n,u.clearRect(0,0,e,n),u.fillStyle=t.c,u.fillRect(0,0,e,n),u.fillStyle=t.d,u.font=t.e+" normal "+t.f+" "+(t.g||100)+"px "+t.h;var r=1;if(""===t.g){var o=.7*e,l=.7*n,i=u.measureText(t.b).width,a=100;r=Math.min(o/i,l/a)}return u.translate(e/2,n/2),u.scale(r,r),u.textAlign="center",u.textBaseline="middle",u.fillText(t.b,0,0),c}function e(){return"#"+("00000"+(16777216*Math.random()<<0).toString(16)).slice(-6)}function n(t){t=t||{};var n=t.size||"128x128",r=t.text||n,o=t.bgcolor||e(),l=t.color||e(),i=t.fstyle||"normal",a=t.fweight||"bold",c=t.fsize||"",u=t.ffamily||"consolas",f={};return n=n.split("x"),2!==n.length&&(n=[128,128]),f.a=n,f.b=r,f.c=o,f.d=l,f.e=i,f.f=a,f.g=c,f.h=u,t=null,f}function r(e){return e=n(e),t(e)}function o(t){return r(t).toDataURL()}function l(t,e,n){return t.getAttribute(e)||n}function i(t){var e,n={},r=t.split("&");for(var o in r){e=r[o].split("=");try{n[e[0]]=decodeURIComponent(e[1])}catch(l){n[e[0]]=e[1]}}return n}function a(t){for(var e,n,r=document.querySelectorAll("img.placeholder"),a=0;a - +
placeholder a qrcode.
@@ -265,6 +265,9 @@
<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">
+ diff --git a/doc/index.html b/doc/index.html index 1c24931..f50233b 100644 --- a/doc/index.html +++ b/doc/index.html @@ -10,7 +10,7 @@ - + diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..a527e9f --- /dev/null +++ b/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/')) +)); \ No newline at end of file diff --git a/index.html b/index.html index 4e7d0e6..6d99a69 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ - placeholder.js - Client side image placeholders / placeholder.cn - Quick and simple image placeholders

placeholder.js renders image placeholders entirely in browser.

the lastest version is 1.65kb, less then 0.92kb after gzip.

Placeholders can have custom colors, fonts, resizing behavior.

Download placeholder.js

Usage

placeholder.getData(opts);

or <img class="placeholder" />

or require("placeholder.js");

Learn more at the placeholder.js GitHub.

How to use? Documents / DEMO.

Placeholder Service

placeholder.cn/{px}/{bg}/{fg}

Just put your image size after our URL and you'll get a placeholder.

1.placeholder.cn/128 2.placeholder.cn/256x128 3.placeholder.cn/137/aaa 4.placeholder.cn/256x128/255/6e9

\ No newline at end of file + placeholder.js - Client side image placeholders / placeholder.cn - Quick and simple image placeholders

placeholder.js renders image placeholders entirely in browser.

the lastest version is 1.65kb, less then 0.92kb after gzip.

Placeholders can have custom colors, fonts, resizing behavior.

Download placeholder.js

Usage

placeholder.getData(opts);

or <img class="placeholder" />

or require("placeholder.js");

Learn more at the placeholder.js GitHub.

How to use? Documents / DEMO.

Placeholder Service

placeholder.cn/{px}/{bg}/{fg}

Just put your image size after our URL and you'll get a placeholder.

1.placeholder.cn/128 2.placeholder.cn/256x128 3.placeholder.cn/137/aaa 4.placeholder.cn/256x128/255/6e9

\ No newline at end of file diff --git a/package.json b/package.json index c179d36..a82828b 100644 --- a/package.json +++ b/package.json @@ -1,12 +1,12 @@ { "name": "placeholder.js", "officialName": "placeholder", - "version": "3.0.0", + "version": "3.1.0", "summary": "1kb library to generate image placeholders on client side", "description": "Holder uses CANVAS to render image placeholders entirely in browser.", "author": { "name": "atool", - "url": "http://www.atool.org/" + "url": "http://www.aTool.org/" }, "homepage": "http://placeholder.cn/", "license": "MIT", @@ -19,7 +19,7 @@ "development", "tools" ], - "main": "placeholder.js", + "main": "dist/placeholder.min.js", "repository": { "type": "git", "url": "https://github.com/hustcc/placeholder.js" @@ -28,9 +28,15 @@ "url": "https://github.com/hustcc/placeholder.js/issues" }, "devDependencies": { + "gulp": "^3.9.0", + "gulp-wrap": "^0.11.0", + "gulp-uglify": "^1.5.3", + "jshint": "^2.9.2", + "gulp-rename": "^1.2.2" }, "scripts": { - "test": "node test/index" + "test": "jshint dist/placeholder.js", + "build": "gulp mini && npm run test" }, "dependencies": { } diff --git a/placeholder.js b/placeholder.js deleted file mode 100644 index e97dca3..0000000 --- a/placeholder.js +++ /dev/null @@ -1,140 +0,0 @@ -/*! - placeholder.js - client side image placeholders - © 2015 Hustcc - http://placeholder.cn/ - Issues: https://github.com/hustcc/placeholder.js/issues - License: MIT -*/ -!function (root, factory) { - if (typeof module === 'object' && module.exports) - module.exports = factory(root); - else - root.placeholder = factory(root); -} (typeof window !== 'undefined' ? window : this, function (window) { - var c, - cc, //公用一个实例,减少内存占用,减少资源消耗 - frame_func = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(func) { - window.setTimeout(func, 1000 / 60); - },//帧动画,做定时任务 - 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() { - var image_eles = document.querySelectorAll('img.placeholder'), img, opts; - for (var i = 0; i < image_eles.length; i++) { - img = image_eles[i]; - //图片没有被处理过,立马处理 - if (! _getAttribute(img, rendered_attr, '')) { - opts = parseUrlOptions(_getAttribute(img, 'options', '')); - img.setAttribute('src', placeholder(opts)); - //处理完成之后标记为处理 - img.setAttribute(rendered_attr, '1'); - } - } - frame_func(render); - } - render();//渲染 - return { - getData: placeholder, - getCanvas: placeholderCanvas - }; -}); diff --git a/placeholder.min.js b/placeholder.min.js deleted file mode 100644 index e5bf657..0000000 --- a/placeholder.min.js +++ /dev/null @@ -1,7 +0,0 @@ -/*! - placeholder.js - client side image placeholders - © 2015 Hustcc - http://placeholder.cn/ - Issues: https://github.com/hustcc/placeholder.js/issues - License: MIT -*/ -;!function(a,b){if(typeof module==="object"&&module.exports){module.exports=b(a)}else{a.placeholder=b(a)}}(typeof window!=="undefined"?window:this,function(j){var k,e,n=j.requestAnimationFrame||j.webkitRequestAnimationFrame||j.mozRequestAnimationFrame||j.oRequestAnimationFrame||j.msRequestAnimationFrame||function(c){j.setTimeout(c,1000/60)},a="placeholder-rendered";function i(t){if(!k||!e){k=document.createElement("canvas");e=k.getContext("2d")}var r=parseInt(t.a[0]),q=parseInt(t.a[1]);k.width=r;k.height=q;e.clearRect(0,0,r,q);e.fillStyle=t.c;e.fillRect(0,0,r,q);e.fillStyle=t.d;e.font=t.e+" normal "+t.f+" "+(t.g||100)+"px "+t.h;var u=1;if(t.g===""){var c=0.7*r,p=0.7*q,o=e.measureText(t.b).width,s=100;u=Math.min(c/o,p/s)}e.translate(r/2,q/2);e.scale(u,u);e.textAlign="center";e.textBaseline="middle";e.fillText(t.b,0,0);return k}function h(){return"#"+("00000"+(Math.random()*16777216<<0).toString(16)).slice(-6)}function f(c){c=c||{};var v=c.size||"128x128",u=c.text||v,w=c.bgcolor||h(),q=c.color||h(),r=c.fstyle||"normal",t=c.fweight||"bold",o=c.fsize||"",s=c.ffamily||"consolas",p={};v=v.split("x");if(v.length!==2){v=[128,128]}p.a=v;p.b=u;p.c=w;p.d=q;p.e=r;p.f=t;p.g=o;p.h=s;c=null;return p}function g(c){c=f(c);return i(c)}function m(c){return g(c).toDataURL()}function l(p,o,c){return p.getAttribute(o)||c}function d(c){var r={},q=c.split("&"),p;for(var o in q){p=q[o].split("=");try{r[p[0]]=decodeURIComponent(p[1])}catch(s){r[p[0]]=p[1]}}return r}function b(){var c=document.querySelectorAll("img.placeholder"),o,q;for(var p=0;p + + return { + getData: placeholder, + getCanvas: placeholderCanvas, + render: render + }; +}); diff --git a/src/src.js b/src/src.js new file mode 100644 index 0000000..4aba35a --- /dev/null +++ b/src/src.js @@ -0,0 +1,119 @@ +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渲染 \ No newline at end of file diff --git a/test/index.js b/test/index.js deleted file mode 100644 index 39f0aed..0000000 --- a/test/index.js +++ /dev/null @@ -1 +0,0 @@ -console.log("TODO");