插入图像并在画布中设置为圆形

时间:2017-07-06 03:39:32

标签: javascript jquery canvas fabricjs

这是我将图像插入画布的代码..

<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>

当我点击并且image / element将是CIRCLE

2 个答案:

答案 0 :(得分:0)

您好我已经创建了一个示例,请看一下,这对您来说很有用。

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>

答案 1 :(得分:0)

尝试clipTo功能

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

此处更新fiddle,半径是上传图片的一半