用canvas 画出圆形图片

/**
* 把图片处理成圆形,如果不是正方形就按最小边一半为半径处理
* @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');
}

传入要处理的图片对象,返回base64链接

 

//window.requestAnimationFrame 的兼容

if(!window.requestAnimationFrame){
    window.requestAnimationFrame = (
      window.webkitRequestAnimationFrame || 
      window.mozRequestAnimationFrame ||
      window.msRquestAniamtionFrame ||
      window.oRequestAnimationFrame || 
      function (callback){
          return setTimeout(callback,Math.floor(1000/60))
    }
  )
}

作者:犯迷糊的小羊
链接:https://www.jianshu.com/p/e70c9cfbdb38
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

 

参考链接:https://blog.csdn.net/fxss5201/article/details/79691923

posted @ 2018-08-15 17:01  哈哈敲敲  阅读(5592)  评论(0编辑  收藏  举报