我是進(jìn)行的uniapp開(kāi)發(fā)所以里邊有部分uniAPI 不需要的小伙伴可根據(jù)需求自行調(diào)整代碼
/**
* 繪制圓角矩形
* @exports
* @param { Object } ctx ctx - canvas組件的繪圖上下文
* @param { Number } x x - 矩形的x坐標(biāo)
* @param { Number } y y - 矩形的y坐標(biāo)
* @param { Number } w w - 矩形的寬度
* @param { Number } h h - 矩形的高度
* @param { Number } r r - 矩形的圓角半徑
* @param { String } c [c = 'transparent'] - 矩形的填充色
*/
export function roundRect (ctx, x, y, w, h, r, c = '#fff') {
if (w < 2 * r) { r = w / 2; }
if (h < 2 * r) { r = h / 2; }
ctx.beginPath();
ctx.fillStyle = c;
ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.lineTo(x + w, y + r);
ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
ctx.lineTo(x + w, y + h - r);
ctx.lineTo(x + w - r, y + h);
ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
ctx.lineTo(x + r, y + h);
ctx.lineTo(x, y + h - r);
ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
ctx.lineTo(x, y + r);
ctx.lineTo(x + r, y);
ctx.fill();
ctx.closePath();
}
/**
* 繪制文字并上色
* @exports
* @param { Object } ctx ctx - canvas組件的繪圖上下文
* @param { Number } text 所需要繪制的文字
* @param { Number } font 文字字體
* @param { Number } color 文字顏色
* @param { Number } left 文字左側(cè)距離
* @param { Number } right 文字頂部距離
* @param { Number } fontSize 字體大小
*/
export function setFont (ctx, text, font, color, left, top, fontSize) {
ctx.font = font;
ctx.setFillStyle(color);
typeof fontSize === 'number' && ctx.setFontSize(fontSize);
ctx.fillText(text, left, top);
}
/**
* 繪制圓形圖片
* @exports
* @param {*} ctx Canvas實(shí)例
* @param {*} src 圖片地址
* @param {*} x x軸坐標(biāo)
* @param {*} y y軸坐標(biāo)
* @param {*} r 圓形半徑
* @description 如果在繪制圖片之后還有需要繪制別的元素囊陡,需啟動(dòng) save() 痒钝、restore() 方法溯革,否則 clip() 方法會(huì)導(dǎo)致之后元素都不可見(jiàn)
*/
export function createCircleImg (ctx, img, x, y) {
uni.getImageInfo({
src: img,
success: ({ width, height }) => {
ctx.save();
let radius, diameter;
radius = width > height ? height / 2 : width / 2;
diameter = radius * 2;
ctx.clearRect(0, 0, diameter, diameter);
ctx.save();
ctx.beginPath();
ctx.arc(radius, radius, radius, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(img, 0, 0, diameter, diameter, 0, 0, diameter, diameter);
ctx.draw();
}
});
}
/**
* 繪制矩形
* @exports
* @param {*} ctx Canvas實(shí)例
* @param {*} w 寬度
* @param {*} h 高度
* @param {*} x x坐標(biāo)
* @param {*} y y坐標(biāo)
* @param {*} color 背景顏色
*/
export function drawRect (ctx, w, h, x, y, color) {
ctx.setFillStyle(color);
ctx.fillRect(x, y, w, h);
}