前段时间写了一个canvas应用——将方形图片处理为圆形 ,最近就想把这个完善一下,所以就再补充一个canvas的圆角矩形处理方式。
例子
你可以直接点击此处查看 例子 ,先一睹为快。
参数
参数 | 默认值 | 描述 |
---|---|---|
img | null | 图片(img)对象 |
type | 0,number类型 | 设置生成图片的大小:0设置生成的图片大小是以图片设置的css大小为准,1设置生成的图片大小是以图片分辨率为准 |
radius | 0,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');
}