/ canvas

赏心悦目的 Material Design

啥也不说先放段小视频:
动手实践下 Material Design 风格的按钮组件

HTML: ```html Document ``` CSS: ```css html,body{ line-height: 100px; text-align: center; background: rgba(245,245,245,.4); }

.btn{
position: relative;
width: 200px;
height: 60px;
border-radius: 4px;
font-size: 24px;
text-align: center;
outline: none;
border: none;
cursor: pointer;
box-shadow: 0 2px 5px 0 rgba(0,0,0,0.26);
-webkit-user-select: none;
}

.btn canvas{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: .3;
transition: opacity .6s ease;
}

.color-teal{
color: #fff;
background: #0eb5b5;
}

.color-teal-reverse{
color: #0eb5b5;
background: #fff;
}

JS:
```javascript
var setMaterial = (function() {
  /***
   * getStyle 获取非行间样样式
   * @param { Object } 目标元素
   * @param { String } 目标属性
   */
  var getStyle = function (obj, attr) {
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr];
  }

  /***
   * createCanvas 动态生成画布
   * @param { Object } Material 化的元素
   */
  var createCanvas = function(obj) {
    var objWidth    = parseInt(getStyle(obj, 'width').slice(0, -2), 10),
        objHeight   = parseInt(getStyle(obj, 'height').slice(0, -2), 10),
        color       = getStyle(obj, 'color'),
        radius      = (objWidth > objHeight) ? objWidth : objHeight,
        currRadius  = 0,
        canvas      = document.createElement('canvas'),
        ctx         = canvas.getContext('2d'),
        isDrawing   = false;

    canvas.width  = objWidth;
    canvas.height = objHeight;

    obj.appendChild(canvas);

    // canvas 绘画
    var draw = function(e) {
      ctx.beginPath();
      ctx.arc( e.offsetX, e.offsetY, currRadius, 0, 2*Math.PI, true);
      ctx.fillStyle = color;
      ctx.fill();
    };

    obj.addEventListener('click', function(e) {
      var timer = {};
      currRadius = isDrawing ? radius : 0;
      timer = setInterval(function() {
        if(currRadius === radius) {
          clearInterval(timer);
          ctx.clearRect( 0, 0, canvas.width, canvas.height);
          currRadius = 0;
          isDrawing = false;
        } else {
          draw(e);
          isDrawing = true;
          currRadius ++;
        }
      }, 2);
    }, false);
  };

  return createCanvas;
}());

;(function() {
  var btn = document.querySelectorAll('.btn');
  for(var i=0; i<btn.length; i++) {
    setMaterial(btn[i]);
  }
}());

最终结果:

原理:

没多大技术性,就是canvas绘图,兼容性嘛 IE9+

其它实现方式(欢迎小伙伴尝试并补充):
  • svg或许是个不错的选择
  • css3嘛试过但碰壁了