参考资料:

http://www.zhangxinxu.com/study/201406/image-border-radius-canvas.html

https://www.jianshu.com/p/9a6ee2648d6f

https://www.cnblogs.com/tarol/p/5414152.html

https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/drawImage

代码具体为网络图片转canvas并取圆角转换成base64

参数img为图片路径

                        var image = new Image()
// 网络图片 处理跨域问题
image.setAttribute('crossOrigin', 'anonymous')
image.src = img
image.onload = () => {
//width、height调用时传入具体像素值,控制大小 ,不传则默认图像大小
var canvas = document.createElement("canvas")
canvas.width = width ? width : image.width
canvas.height = height ? height : image.height
var ctx = canvas.getContext("2d")
// // 创建图片纹理
var pattern = ctx.createPattern(image, "no-repeat")
// 如果是正方形图片
if (canvas.width == canvas.height) {
console.log('正方形')
// // 绘制一个圆
ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, 2 * Math.PI)
// // 填充绘制的圆
ctx.fillStyle = pattern
ctx.fill()
}else {
console.log('长方形')
ctx.save();
ctx.arc(image.width/2, image.height/2, Math.min(image.width, image.height) / 2, 0, 2 * Math.PI);
// 从画布上裁剪出这个圆形
ctx.clip();
canvas.width = width ? width : image.width/2
canvas.height = height ? height : image.width/2
ctx.drawImage(image, 0, 0, Math.min(image.width, image.height) / 2, Math.min(image.width, image.height) / 2);
ctx.restore();
ctx.clearRect(0, 0, canvas.width, canvas.height); //清空画布
// // 绘制一个圆
ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, 2 * Math.PI)
// // 填充绘制的圆
ctx.fillStyle = pattern
ctx.fill()
}
var dataURL = canvas.toDataURL()
_this.avatar = dataURL

  

效果:

最新文章

  1. 【Mybatis框架】查询缓存(一级缓存)
  2. SQL最简单分类简介
  3. PHP+jQuery+Ajax实现用户登录与退…
  4. js深入研究之函数内的函数
  5. Qt入门-字符串类QString
  6. Promise基础
  7. Hive函数:LAG,LEAD,FIRST_VALUE,LAST_VALUE
  8. [bzoj4161]Shlw loves matrix I
  9. 前端笔记之Canvas
  10. Apache Spark 章节1
  11. web网页错误代码的含义
  12. CentOS7 + Django2.1 + uwsgi + nginx配置
  13. bzoj 1951
  14. JS实现缓动动画效果
  15. Jquery中父,子页面之间元素获取及方法调用
  16. JAVA开发工程师面试(1)
  17. gcc常用命令使用
  18. php7安装redis拓展
  19. css3之transform属性实现div不定宽高垂直水平居中
  20. Hibernate学习笔记二:常用映射配置

热门文章

  1. 手机连接电脑,使用adb命令
  2. CoverflowJS
  3. python中用*和**解析数据
  4. python基础--面向对象之多态
  5. 网站换VPS wdcp操作记录
  6. 渗透测试环境搭建以及使用sqlmap获取mysql用户数据库密码
  7. PTA(Basic Level)1010.一元多项式求导
  8. 【转帖】大话Spring Cloud
  9. isinstance与issubclass,反射
  10. PostgreSQL-临时表空间与配置表