这篇文章主要为大家展示了“js中canvas如何实现圆角图片”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“js中canvas如何实现圆角图片”这篇文章吧。
圆角图片的代码实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body > <div > <!--通过style方式为canvas设置宽高在火狐浏览器上导致绘制内容纵向拉伸。。。--> <canvas id="drawing" width="400px" height="400px">canvas to draw</canvas> <pre id="container" /> <img src=//img.jbzj.com/file_images/article/202109/202191115608734.jpg> </div> </body> <script type="text/javascript"> window.οnlοad=function () { var drawing = document.getElementById('drawing'); if (drawing.getContext) { print('support') addRoundRectFunc(); var context = drawing.getContext('2d'); draw(context); } else { print('not ') } } function draw(context) { context.fillStyle = 'red'; var image = document.images[0]; context.roundRect(0,0,image.width/2,image.height/2,30,true) context.globalCompositeOperation='source-in'; context.drawImage(image, 0, 0, image.width / 2, image.height / 2) // toImage(); } function addRoundRectFunc() { CanvasRenderingContext2D.prototype.roundRect = function (x, y, width, height, radius, fill, stroke) { if (typeof stroke == "undefined") { stroke = true; } if (typeof radius === "undefined") { radius = 5; } this.beginPath(); this.moveTo(x + radius, y); this.lineTo(x + width - radius, y); this.quadraticCurveTo(x + width, y, x + width, y + radius); this.lineTo(x + width, y + height - radius); this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height); this.lineTo(x + radius, y + height); this.quadraticCurveTo(x, y + height, x, y + height - radius); this.lineTo(x, y + radius); this.quadraticCurveTo(x, y, x + radius, y); this.closePath(); if (stroke) { this.stroke(); } if (fill) { this.fill(); } }; } function toImage() { var imageUri = drawing.toDataURL('image/png'); var imageTag = document.createElement('img'); imageTag.style = 'margin:10px;width:200px;height:200px' imageTag.src = imageUri; document.body.appendChild(imageTag) } function print(txt) { document.getElementById("container").innerHTML += ('\n') + txt; } document.body.onclick = function () { window.location.reload() } console.log = print; </script> </html>
效果图:
补充一段使用小代码:canvas 生成圆角图片(头像等)
circleImg(ctx, img, x, y, r) { ctx.save(); var d =2 * r; var cx = x + r; var cy = y + r; ctx.arc(cx, cy, r, 0, 2 * Math.PI); ctx.clip(); ctx.drawImage(img, x, y, d, d); ctx.restore(); }
以上是“js中canvas如何实现圆角图片”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。