canvas绘制圆角头像
使用 CanvasRenderingContext2D.createPattern()
缺点:
- 不能调整背景图大小
通过裁剪画布部分区域实现
const cvs = document.querySelector('#cvs')
const ctx = cvs.getContext('2d')
// 封装了一个简单的方法
function circleImg(ctx, img, x, y, r) {
ctx.save();
ctx.beginPath()
var d =2 * r;
var cx = x + r;
var cy = y + r;
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
ctx.clip();
ctx.drawImage(img, x, y, d, d);
ctx.restore();
}
var img = new Image();
img.src = 'https://www.canvasapi.cn/assets/images/logo.png';
var img2 = new Image()
img2.src = 'https://imgse.com/content/images/system/home_cover_1601010270144_8921bc.jpg'
circleImg(ctx, img2, 100, 20, 50);
ctx.moveTo(200, 200)
ctx.lineTo(300, 240)
ctx.stroke()
circleImg(ctx, img, 220, 20, 50);
绘制带有圆角的矩形
const cvs = document.querySelector('#cvs')
const ctx = cvs.getContext('2d')
const drawRect = ({ctx, start, width,height,radius, contentInRect}) => {
ctx.save()
ctx.beginPath()
const caculateLong = height/2 > width/2 ? width/2 : height/2
const usedRadius = caculateLong> radius ? radius : caculateLong
const topLeftPoint = [start[0] + usedRadius, start[1] ]
const topRightPoint = [start[0] + width -usedRadius, start[1]]
const topRight = [start[0] + width , start[1]]
const rightBottom = [start[0] + width, start[1]+height]
const leftBottom = [start[0], start[1] + height]
const LeftBottomPoint = [start[0], start[1] - usedRadius + height]
const LeftTopPoint = [start[0], start[1] + usedRadius]
const BottomLeftPoint = [start[0] + usedRadius, start[1] + height]
const BottomRightPoint = [start[0] - usedRadius + width, start[1] + height]
const RightBottomPoint = [start[0]+width, start[1] - usedRadius + height]
const RightTopPoint = [start[0]+width, start[1] + usedRadius]
ctx.moveTo(...topLeftPoint)
ctx.lineTo(...topRightPoint)
ctx.quadraticCurveTo(...topRight,...RightTopPoint)
ctx.lineTo(...RightBottomPoint)
ctx.quadraticCurveTo(...rightBottom,...BottomRightPoint)
ctx.lineTo(...BottomLeftPoint)
ctx.quadraticCurveTo(...leftBottom,...LeftBottomPoint)
ctx.lineTo(...LeftTopPoint)
ctx.quadraticCurveTo(...start, ...topLeftPoint)
ctx.closePath()
ctx.clip();
if(!contentInRect){
ctx.restore();
}else {
contentInRect.finally(()=> {
ctx.restore();
})
}
}
const img = new Image()
img.src = 'https://www.canvasapi.cn/assets/images/logo.png'
img.onload = () => {
drawRect({
ctx,
start: [10,10],
width: 100,
height: 50,
radius: 20,
contentInRect: new Promise(resolve=> {
setTimeout(()=> {
ctx.drawImage(img, 10, 10, 200, 50); resolve('')
})
})
})
// ctx.drawImage(img, 15, 15, 200, 50);
setTimeout(()=> {
drawRect({
ctx,
start: [100,100],
width: 100,
height: 50,
radius: 20,
contentInRect: new Promise(resolve=> {
setTimeout(()=> {
ctx.drawImage(img, 100, 100, 200, 50); resolve('')
})
})
})
},1000)
}