2016-03-27 26 views
-2

我是新來的編寫網頁的腳本。我正在尋找一種JavaScript或Jquery插件,以六角形(附圖)的形式在(自定義提供的)尺寸上裁剪圖像。 理想情況下,如果可以通過CSS完成,那將是非常好的,但如果沒有,那麼任何JS或JQuery插件都可以工作。JS Plug in or CSS以六角形切割圖像

enter image description here

+1

Hi @Praveen Kumar, 你已經共享的鏈接將span或div轉換爲六角形。如果您在本文中閱讀了我的描述,我正在尋找將圖像轉換爲hexa的解決方案。 – user3772369

+0

我已重新打開帖子好友。謝謝你讓我知道。祝一切順利。 –

+0

鏈接的URL顯示以多邊形形狀裁剪的圖像。你是否需要將圖像切割成六邊形,以便如果將它保存起來就可以得到六角形?你不能用CSS做到這一點。 Imho,只能用畫布和Javascript。 –

回答

2

這是我在你想要的功能的嘗試:

function polygonalCrop(options) { 
    function extend(a, b){ 
     b=b||{}; 
     for(var key in b) 
      if(b.hasOwnProperty(key)) 
       a[key] = b[key]; 
     return a; 
    } 

    options=extend({ 
     url:null, 
     sides:8, 
     angle:0, 
     centerX:null, 
     centerY:null, 
     radius:null, 
     outlineColor:null, 
     outlineThickness:null, 
     success:function(url){}, 
     fail:function(ev){} 
    },options); 
    if (!options.url) throw 'options needs an image URL as url property'; 
    var img=new Image(); 
    img.setAttribute('crossOrigin', 'anonymous'); 
    img.onload=function() { 
     var w=this.width; 
     var h=this.height; 
     var canvas=document.createElement('canvas'); 
     canvas.width=w; 
     canvas.height=h; 
     var ctx=canvas.getContext('2d'); 
     if (options.centerX===null) { 
      options.centerX=w/2; 
     } 
     if (options.centerY===null) { 
      options.centerY=h/2; 
     } 
     var ang=2*Math.PI/options.sides; 
     var len=Math.sin(ang/2)*2; 
     if (options.radius===null) { 
      options.radius=Math.min(w/2,h/2)*Math.cos(ang/2); 
     } 
     ctx.translate(options.centerX,options.centerY); 
     ctx.rotate(options.angle); 
     if (options.outlineThickness) ctx.lineWidth=options.outlineThickness; 
     if (options.outlineColor) ctx.strokeStyle=options.outlineColor; 
     ctx.moveTo(-len/2,-options.radius); 
     for (var i=0; i<2*Math.PI; i+=ang) { 
      ctx.rotate(ang); 
      ctx.lineTo(len/2,-options.radius); 
     } 
     ctx.closePath(); 
     if (options.outlineThickness && options.outlineColor) ctx.stroke(); 
     ctx.clip(); 
     ctx.rotate(2*Math.PI-i-options.angle); 
     ctx.translate(-options.centerX,-options.centerY); 
     ctx.drawImage(this,0,0); 
     options.success(ctx.canvas.toDataURL()); 
    }; 
    img.onerror=function() { alert('there was an error loading the image'); }; 
    img.src=options.url; 
} 

它所做的是把你的網址和裁剪區域的值,並返回裁剪圖像的傳輸數據的URL。你可以在這裏看到它的動作:https://jsfiddle.net/psrec1b5/2/

+0

非常感謝先生......只是一個簡單的問題。我如何讓它看起來完全像我在原始帖子中分享的圖片? – user3772369

+0

我已經更新了答案和小提琴。使用outlineThickness和outlineColor屬性繪製輪廓。使用角度旋轉六角形。 –