1. 程式人生 > 程式設計 >js canvas實現圓角圖片

js canvas實現圓角圖片

本文例項為大家分享了 canvas實現圓角圖片的具體程式碼,供大家參考,具體內容如下

圓角圖片的程式碼實現:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="background: rgba(199,237,204,1)">
 
<div style="display:flex; flex-direction: row">
 
    <!--通過
style方式為canvas設定寬高在火狐瀏覽器上導致繪製內容縱向拉伸。。。--> <canvas id="drawing" width="400px" height="400px">canvas to draw</canvas> <pre id="container" style="margin: 10px"/> <img src=//img.jbzj.com/file_images/article/202109/202191115608734.jpg> </div> </body> <script type="text/"> window.nlad=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,image.width/2,image.height/2,30,true) context.globalCompositeOperation='source-in'; context.drawImage(image,image.width / 2,image.height / 2) // toImage(); } function addRoundRectFunc() { CanvasRenderingContext2D.prototype.roundRect = function (x,y,width,height,BSZimEZADW
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,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,x,y + height - radius); this.lineTo(x,y + radius); this.quadraticCurveTo(x,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>

效果圖:

js canvas實現圓角圖片

補充一段使用小程式碼:canvas 生成圓角圖片(頭像等)

circleImg(ctx,img,r) {
    ctx.save();
    var d =2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx,cy,r,2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img,d,d);
    ctx.restore();
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。