canvas应用——圆角矩形图片

前段时间写了一个canvas应用——将方形图片处理为圆形 ,最近就想把这个完善一下,所以就再补充一个canvas的圆角矩形处理方式。

例子

你可以直接点击此处查看 例子 ,先一睹为快。

参数

参数默认值描述
imgnull图片(img)对象
type0,number类型设置生成图片的大小:0设置生成的图片大小是以图片设置的css大小为准,1设置生成的图片大小是以图片分辨率为准
radius0,number类型圆角矩形的圆角半径

代码

/**
 * 把图片处理成圆角矩形
 * @param  {object} img 图片(img)对象
 * @param  {number} type 设置生成图片的大小:0设置生成的图片大小是以图片设置的css大小为准,1设置生成的图片大小是以图片分辨率为准,默认值为0
 * @param  {number} radius 圆角矩形的半径,默认值为0
 * @return {string}     return base64 png图片字符串
 */
function circleRect_image(option) {
    var img = option.img;
    var type = option.type || 0;
    var radius = option.radius || 0;
    var imgSize, canvas, ctx;
    if (type){
        imgSize = {
            width: img.naturalWidth,
            height: img.naturalHeight
        }
    }else{
        imgSize = {
            width: img.width,
            height: img.height
        }
    }
    canvas = document.createElement('canvas');
    if (!canvas.getContext) { // 判断浏览器是否支持canvas,如果不支持在此处做相应的提示
        console.log('您的浏览器版本过低,暂不支持。');
        return false;
    }
    canvas.width = imgSize.width;
    canvas.height = imgSize.height;
    ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, imgSize.width, imgSize.height);
    ctx.save();
    ctx.beginPath();
    roundedRect(ctx, 0, 0, imgSize.width, imgSize.height, radius);
    ctx.clip();  // 通过裁剪得到圆角矩形 
    if(type){
        ctx.drawImage(img, 0, 0, imgSize.width, imgSize.height, 0, 0, imgSize.width, imgSize.height);        
    }else{
        ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, imgSize.width, imgSize.height);
    }
    ctx.restore();

    // 画圆角矩形
    function roundedRect(ctx, x, y, width, height, radius) {
        ctx.strokeStyle = "#fff";
        ctx.beginPath();
        ctx.moveTo(x, y + radius);
        ctx.lineTo(x, y + height - radius);
        ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
        ctx.lineTo(x + width - radius, y + height);
        ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
        ctx.lineTo(x + width, y + radius);
        ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
        ctx.lineTo(x + radius, y);
        ctx.quadraticCurveTo(x, y, x, y + radius);
        ctx.stroke();
    }
    return canvas.toDataURL('image/png');
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值