h5中使用canvas把图片缩放并且剪切成圆形

来源:赵克立博客 分类: HTML5 标签:CanvasHTML5canvas发布时间:2016-11-28 11:47:50最后更新:2019-10-31 21:20:44浏览:10511
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-10-31 21:20:44
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章

有两个函数一个缩放一个剪切成圆,都返回一个base64格式的png图片,直接放到image的src标签就可以使用

原图

blob.png

缩放剪切成圆过后

blob.png

/**
 * 生成图片的缩略图
 * @param  {[type]} img    图片(img)对象或地址
 * @param  {[type]} width  缩略图宽
 * @param  {[type]} height 缩略图高
 * @return {[type]}        return base64 png图片字符串
 */
function thumb_image(img, width, height) {
	if (typeof img !== 'object') {
		var tem = new Image();
		tem.src = img;
		img = tem;
	}
	var _canv = document.createElement('canvas');
	_canv.width = width;
	_canv.height = height;
	_canv.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
	return _canv.toDataURL();
}
/**
 * 把图片处理成圆形,如果不是正方形就按最小边一半为半径处理
 * @param  {[type]} img 图片(img)对象或地址
 * @return {[type]}     return base64 png图片字符串
 */
function yuan_image(img) {
	if (typeof img !== 'object') {
		var tem = new Image();
		tem.src = img;
		img = tem;
	}
	var w, h, _canv, _contex, cli;
	if (img.width > img.height) {
		w = img.height;
		h = img.height;
	} else {
		w = img.width;
		h = img.width;
	}
	_canv = document.createElement('canvas');
	_canv.width = w;
	_canv.height = h;
	_contex = _canv.getContext("2d");
	cli = {
		x: w / 2,
		y: h / 2,
		r: w / 2
	};
	_contex.clearRect(0, 0, w, h);
	_contex.save();
	_contex.beginPath();
	_contex.arc(cli.x, cli.y, cli.r, 0, Math.PI * 2, false);
	_contex.clip();
	_contex.drawImage(img, 0, 0);
	_contex.restore();
	return _canv.toDataURL();
}



微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python