canvas画圆形头像(clip,globalCompositeOperation的使用)

实现圆形头像的几种方式
clip实现蒙版效果
使用clip会对画布设置一个绘制范围,clip后的操作都只会在这个绘制范围里显示,超出这个范围的绘制操作将不会在画布中显示。代码如下:

var canvas = document.getElementById('canvas')
canvas.width = 300
canvas.height = 300
var ctx = canvas.getContext('2d')
var img = new Image()
img.src = 'http://h.hiphotos.baidu.com/zhidao/pic/item/6f061d950a7b02086c89030660d9f2d3562cc890.jpg'
img.onload = function () {
    // 通过arc来绘制一个圆形区域
    ctx.arc(150, 150, 60, 0, 2 * Math.PI)
    ctx.clip()
    ctx.drawImage(img, 90, 90, 120, 120)
}

得到效果:
在这里插入图片描述
globalCompositeOperation组合实现
globalCompositeOperation用于控制源图像在目标图像上的显示方式。

1、源图像: 指你准备绘制到画布上的图像
2、目标图像:在画布上已经绘制的图像
在这里插入图片描述

var canvas = document.getElementById('canvas')
canvas.width = 300
canvas.height = 300
var ctx = canvas.getContext('2d')
var img = new Image()
img.src = 'http://h.hiphotos.baidu.com/zhidao/pic/item/6f061d950a7b02086c89030660d9f2d3562cc890.jpg'
img.onload = function () {
    // 通过arc来绘制一个圆形区域
    ctx.drawImage(img, 90, 90, 120, 120)
    ctx.globalCompositeOperation = 'destination-in'
    ctx.fillStyle = '#fff'
    ctx.arc(150, 150, 60, 0, 2 * Math.PI)
    ctx.fill()
    ctx.globalCompositeOperation = 'lighter'
    ctx.fillStyle = '#000'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
}

效果如下:
在这里插入图片描述

当我们使用globalCompositeOperation时,绘制区域的时候需要填充颜色,如果没有填充颜色或者填充颜色的透明度为0时并不会实现组合的效果。

增加头像的羽化效果,通过createRadialGradient实现
绘制渐变效果
通过createRadialGradient和createLinearGradient实现颜色的渐变效果,其中createRadialGradient是径向渐变,createLinearGradient是线性渐变。

createRadialGradient用于创建放射性/圆形渐变,使用addColorStop来定义颜色的过渡,渐变的颜色可以用于填充绘制的矩形,圆形线条和文本。代码如下:

let grad = ctx.createRadialGradient(150, 150, 40, 150, 150, 60)
grad.addColorStop(0, 'rgba(255, 255, 255, 1)')
grad.addColorStop(1, 'rgba(255, 255, 255, 0)')
ctx.arc(150, 150, 60, 0, 2 * Math.PI)
ctx.fillStyle = grad
ctx.fill()

其中createRadialGradient有六个参数(x0,y0,r0,x1,y1,r1),前三个参数表示渐变开始时的圆,后三个参数表示渐变结束时的圆。

2、createLinearGradient用户绘制线性渐变,有四个参数(x0,y0,x1,y1),分别表示两个点,通过两点连线确定颜色渐变的方向,使用addColorStop来定义多种颜色的过渡。案例:

let grad = ctx.createLinearGradient(10, 10, 100, 100)
grad.addColorStop(0, 'rgba(255, 255, 255, 1)')
grad.addColorStop(1, 'rgba(255, 255, 255, 0)')
ctx.fillStyle = grad
ctx.fillRect(5, 5, 100, 50)

这边由于绘制的是圆形头像,所以使用createRadialGradient来实现,修改上方代码如下:

// 替换掉 ctx.fillStyle = '#fff'
let grad = ctx.createRadialGradient(150, 150, 40, 150, 150, 60)
grad.addColorStop(0, 'rgba(255, 255, 255, 1)')
grad.addColorStop(1, 'rgba(255, 255, 255, 0)')
ctx.fillStyle = grad

得到效果
在这里插入图片描述

可以通过设置createRadialGradient的开始渐变圆大小或者使用addColorStop增加中间过度颜色来控制渐变范围

参考文章:
https://blog.csdn.net/qq_30668579/article/details/51495909
https://blog.csdn.net/laijieyao/article/details/41862473

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值