zoukankan      html  css  js  c++  java
  • canvas实现圆角、圆框图片

    参考资料:

    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
    

      

    效果:

  • 相关阅读:
    Linux CPU监控指标
    Elasticsearch强大的聚合功能Facet
    业务逻辑层的设计
    数据结构中的棧在C#中的实现
    使用WPF教你一步一步实现连连看
    ASP.NET之旅—再一次与ASP谋面
    每日一帖示例程序(使用TWebBrowser基于HTML做)
    在程序异常中记录堆栈信息(使用ExWatcher)
    获取TBitMap图像缓冲区,提高图像处理速度
    delphi实现穿XP防火墙
  • 原文地址:https://www.cnblogs.com/lanshengzhong/p/8609945.html
Copyright © 2011-2022 走看看