首页 > 技术文章 > 用Js+css3实现图片旋转,缩放,裁剪,滤镜

marszhw 2016-10-21 15:32 原文

还是前端图片的老话题,花了半天时间,东拼西凑,凑出个demo,优点在于代码少,核心代码就6行,目前刚做了旋转,缩放,裁剪,滤镜要js做,网络上也有现成的代码,

但是想做到自定义的滤镜咋办呢?这还要从底层了解滤镜的实现才行~实际上,我们无论用C++,还是java实现了滤镜,都能移植到js端,原理是相通的。

总之,再次强调,原理很重要,掌握了原理,你就可以任性了。

可以放到http://runjs.cn/里做验证,好棒的在线工具~

<!DOCTYPE html>
<html>
  <head>
 <meta charset="utf-8" />
 <title>js+css3</title>
  </head>
 <style type="text/css">
  .clipzone
  {
   position:relative;
   width:400px;
   height:400px;
   overflow:hidden;
  }
  .clipped
  {
   position:absolute;
  }
 </style>
  <body>
  <input type="button" value="rotate" onclick="rotate(20);"/>
  <input type="button" value="scale" onclick="scale(1.5);"/>
  <input type="button" value="clip" onclick="clip();"/>
  <input type="button" value="support_canvas_test" onclick="support_canvas_test();"/>
    <div class="clipzone" id="testdiv">
  <img class="clipped"  id="image1" src="http://www.artup.com/img/icon35.png" width="282" height="220" >
  </div>
    <script type="text/javascript">
   var totalrotate = 0;
   var totalscale = 0;
   function rotate(sum){
   totalrotate = totalrotate + sum;
      var obj=document.getElementById("image1");
   obj.style.webkitTransform="rotate("+totalrotate+"deg)";
     }
   function scale(sum){
   totalscale = totalscale + sum;
      var obj=document.getElementById("image1");
   obj.style.webkitTransform="scale("+totalscale+")";
     }
   function clip(){
      var obj=document.getElementById("image1");
   obj.style.clip = "rect(20px, auto, auto, 10px)"; 
     }
  function support_canvas_test(){ 
   var elem = document.createElement('canvas');
   var context = elem.getContext('2d');  
   alert(typeof context.fillText === 'function'?"support":"not support");  
  }
  var support_css3 = (function() {
   var div = document.createElement('div'),
    vendors = 'ms o moz webkit'.split(' '),
    len = vendors.length;
    
  return function(prop) { 
   if ( prop in div.style ) return true; 
   len = vendors.length;
   while(len--) {
     if ( vendors[len] + prop in div.style ) {
     return true; 
     } 
   } 
   return false;
     }; 
 })();
 
    </script>
  </body>
</html>

推荐阅读