图片裁剪-内凹圆形

最近作了一个好玩的东西,分享给你们。css

bendImage.png

有一个需求,就是要把图片两侧裁剪成向内凹的圆形(如图),而且两侧凹处不能遮挡背景。canvas

预览地址:demo.dyrily.cn/bendImage/bash

对于这种异形的图片,css貌似有点棘手。因而乎,祭出神器:canvas。ui

这个需求的难点在于如何让裁剪的圆弧经过固定的点,也就是图片边角。url

img2.png

这里用的方法是勾股定理来计算裁剪圆的半径。spa

/**
 * @param canvas element元素
 * @param option
 *      width       canvas的宽
 *      height      canvas的高
 *      url         裁剪图片的连接
 *      distance    内凹的距离
 */
function bendImage(canvas, option) {
    canvas.width = option.width;
    canvas.height = option.height;
    var ctx = canvas.getContext('2d');
    // 经过勾股定理化简后的表达式
    var radius = (option.distance + Math.pow(option.height, 2) / option.distance / 4) / 2;
    var image;
    if (bendImage.image && bendImage.image.src === option.url) {
        image = bendImage.image;
        draw();
        return;
    }
    image = new Image();
    image.src = option.url;
    image.onload = function () {
        bendImage.image = image;
        draw();
    };

    function draw() {
        ctx.drawImage(image, 0, 0, option.width, option.height);
        ctx.globalCompositeOperation = 'destination-out';
        ctx.arc(option.distance - radius, option.height / 2, radius, 0, Math.PI * 2);
        ctx.fill();
        ctx.arc(option.width + radius - option.distance, option.height / 2, radius, 0, Math.PI * 2);
        ctx.fill();
    }
}
复制代码

原创文章,转载注明出处,感谢。code

相关文章
相关标签/搜索