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
    

      

    效果:

  • 相关阅读:
    Porter Stemming Algorithm
    Hook API to detect memory leak
    Are tuples more efficient than lists in Python?
    boost::intrusive_ptr VS boost::shared_ptr
    How Python GC deal with referencecycles?
    LINQ排序数组
    Sublime Text 2 (Version 2.0.1 build 2217) x64 破解注册方法
    GC in C# and Python
    Python中的else
    Managed C++ Destructor
  • 原文地址:https://www.cnblogs.com/lanshengzhong/p/8609945.html
Copyright © 2011-2022 走看看