2017-07-06 50 views
0

這是我的代碼中插入圖像以帆布..插入圖片,並在畫布設置爲圓形

<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script> 
<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button> 
<input type="file" id="file"> 
     <canvas id="canvas" width="750" height="550"></canvas> 
     <a href='' id='txt' target="_blank">Click Me!</a> 
     <br /> 
     <img id="preview" /> 

https://jsfiddle.net/javasalden/yn04k565/

如何完成按鈕:

<button onclick="addTexttitle()" type="button" class="text-left btn-block btn white">Set Image To Circle</button> 

當我點擊圖像/元素將是CIRCLE

回答

0

嘗試clipTo功能

img.set({ 
clipTo: function (ctx) { 
    ctx.arc(0, 0, radius, 0, Math.PI * 2, true); 
} 
}); 

這裏被更新fiddle,半徑上傳圖像的一半

0

嗨我已經創建了一個示例,請看看它,這是definatley對你有用。

var createCache = function(requestFunction) { 
 
    var cache = {}; 
 
    return function(key, callback) { 
 
     if (!cache[key]) { 
 
      cache[key] = $.Deferred(function(defer) { 
 
       requestFunction(defer, key); 
 
      }).promise(); 
 
     } 
 
     return cache[key].done(drawImg); 
 
    }; 
 
}; 
 

 

 
var loadImage = createCache(function(defer, url) { 
 
    var image = new Image(); 
 
    function cleanUp() { 
 
     image.onload = image.onerror = null; 
 
    } 
 
    
 
    defer.then(cleanUp, cleanUp); 
 
    image.onload = function() { 
 
     defer.resolve(url); 
 
    }; 
 
    image.onerror = defer.reject; 
 
    image.src = url; 
 
}); 
 

 

 
var drawImg = function(img) { 
 
    var tmpCanvas = document.createElement('canvas'), 
 
     tmpCtx = tmpCanvas.getContext('2d'), 
 
     image = new Image(); 
 
    
 
    
 
    image.src = img; 
 
    tmpCanvas.width = image.width*2; 
 
    tmpCanvas.height = image.height*2; 
 
    
 
    // draw the cached images to temporary canvas and return the context 
 
    tmpCtx.save(); 
 
     tmpCtx.beginPath(); 
 
      tmpCtx.arc(2*24, 2*24, 2*24, 0, Math.PI*2, true); 
 
     tmpCtx.closePath(); 
 
     tmpCtx.clip(); 
 

 
    tmpCtx.drawImage(image, 0, 0, 4*24+2, 4*24+2); 
 
    
 
     tmpCtx.beginPath(); 
 
      tmpCtx.arc(0, 0, 2, 0, Math.PI*2, true); 
 
      tmpCtx.clip(); 
 
     tmpCtx.closePath(); 
 
    tmpCtx.restore(); 
 

 
    $('body').append(tmpCanvas); 
 
}; 
 

 

 
var cacheImgs = function() { 
 
    var imgs = [ 
 
     
 
     'https://cdn.pixabay.com/photo/2017/01/06/19/15/soap-bubble-1958650_960_720.jpg' 
 
    ]; 
 
    
 
    for (var i = 0; i < imgs.length; i++) { 
 
     var img = loadImage(imgs[i])/*.done(drawImg(imgs[i]))*/; 
 
     // .done callback is what sends the canvases to where they need to go 
 
    } 
 
} 
 
cacheImgs();
canvas { float: left; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> 
 
<body></body>

+0

我覺得OP一直在尋找一種解決方案fabric.js解決問題。 – Blindman67

+0

可能是他沒有體型,所以我認爲這可能是有用的。它工作得很好。 –

+0

感謝bro @ Blindman67更新代碼並刪除不必要的控制檯。 –

相關問題