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