上段时间在项目中需要将方形图片处理为圆形图片,你可能会说直接用css设置border-radius: 50%就可以了,但是项目中还要将此图片的圆形图片作为一部分利用canvas将其绘制到一张背景图上面,所以就有了为何要用canvas来处理了。
我们知道 是 HTML5 新增的元素,可用于通过使用JavaScript中的脚本来绘制图形。我将本例中的主要处理函数封装为一个方法,可以直接使用。
关于版本更新导致的参数更改详情可查看 此处 。
你可以直接点击此处查看 例子 ,先一睹为快。
以下内容更新于2018-06-05:原型图片的改良版
参数 | 默认值 | 描述 |
---|---|---|
img | null | 图片(img)对象 |
type | 0,number类型 | 设置生成图片的大小:0设置生成的图片大小是以图片设置的css大小为准,1设置生成的图片大小是以图片分辨率为准 |
/**
* 把图片处理成圆形,如果不是正方形就按最小边一半为半径处理
* @param {object} imgObj 图片(img)对象
* @param {number} imgType 设置生成图片的大小:0设置生成的图片大小是以图片设置的css大小为准,1设置生成的图片大小是以图片分辨率为准,默认值为0
* @return {string} return base64 png图片字符串
*/
function circle_image_v2(img, imgType) {
var type = imgType || 0;
var radius, diameter, canvas, ctx, natural;
if (type) {
if (img.naturalWidth > img.naturalHeight) {
radius = img.naturalHeight / 2;
} else {
radius = img.naturalWidth / 2;
}
} else {
if (img.width > img.height) {
radius = img.height / 2;
} else {
radius = img.width / 2;
}
if (img.naturalWidth > img.naturalHeight) {
natural = img.naturalHeight;
} else {
natural = img.naturalWidth;
}
}
diameter = radius * 2;
canvas = document.createElement('canvas');
if (!canvas.getContext) { // 判断浏览器是否支持canvas,如果不支持在此处做相应的提示
console.log('您的浏览器版本过低,暂不支持。');
return false;
}
canvas.width = diameter;
canvas.height = diameter;
contex = canvas.getContext("2d");
contex.clearRect(0, 0, diameter, diameter);
contex.save();
contex.beginPath();
contex.arc(radius, radius, radius, 0, Math.PI * 2, false);
contex.clip();
if (type) {
contex.drawImage(img, 0, 0, diameter, diameter, 0, 0, diameter, diameter);
} else {
contex.drawImage(img, 0, 0, natural, natural, 0, 0, diameter, diameter);
}
contex.restore();
return canvas.toDataURL('image/png');
}
以下为旧版内容。
参数 | 描述 |
---|---|
img | 图片(img)对象 |
oldImgWidth | 原始图片(img)的实际宽度(非css设置的) |
oldImgHeight | 原始图片(img)的实际高度(非css设置的) |
/**
* 把图片处理成圆形,如果不是正方形就按最小边一半为半径处理
* @param {[type]} img 图片(img)对象
* @param {[number]} oldImgWidth 原始图片(img)的实际宽度(非css设置的)
* @param {[number]} oldImgHeight 原始图片(img)的实际高度(非css设置的)
* @return {[type]} return base64 png图片字符串
*/
function circle_image(img, oldImgWidth, oldImgHeight) {
var width, height, canvas, contex, circle;
if (img.width > img.height) {
width = img.height;
height = img.height;
} else {
width = img.width;
height = img.width;
}
canvas = document.createElement('canvas');
if (!canvas.getContext) { // 判断浏览器是否支持canvas,如果不支持在此处做相应的提示
console.log('您的浏览器版本过低,暂不支持。');
return false;
}
canvas.width = width;
canvas.height = height;
contex = canvas.getContext("2d");
circle = {
x: width / 2,
y: height / 2,
r: width / 2
};
contex.clearRect(0, 0, width, height);
contex.save();
contex.beginPath();
contex.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, false);
contex.clip();
contex.drawImage(img, 0, 0, oldImgWidth, oldImgHeight, 0, 0, width, height);
contex.restore();
return canvas.toDataURL('image/png');
}