canvas實現圖片圓邊-直角
阿新 • • 發佈:2021-01-21
canvas實現圖片圓邊
參考資料: https://www.cnblogs.com/lanshengzhong/p/8609945.html
效果
原始碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>實現圓角</title> </head> <body> <strong>這是原圖</strong> <p><img src="http://image.zhangxinxu.com/image/study/s/s256/mm1.jpg" width="256" height="191"></p> <strong>這是Canvas實現</strong> <p>圓角大小:<span class="range-txt"> 0 <input id="radiusInput" type="range" min="0" max="92" value="0"> 92</span></p> <canvas id="canvas" width="256" height="191"></canvas> <script type="text/javascript"> //圓角矩形 CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) { var min_size = Math.min(w, h); if (r > min_size / 2) r = min_size / 2; // 開始繪製 this.beginPath(); this.moveTo(x + r, y); this.arcTo(x + w, y, x + w, y + h, r); // this.arcTo(x + w, y + h, x, y + h, r); this.lineTo( x + w , y + h ) // 直角不變化 this.arcTo(x, y + h, x, y, r); this.arcTo(x, y, x + w, y, r); this.closePath(); return this; } // canvas元素, 圖片元素 var canvas = document.querySelector("#canvas"), image = new Image(), input = document.getElementById("radiusInput"); var context = canvas.getContext("2d"); var draw = function(obj) { // 建立圖片紋理 var pattern = context.createPattern(obj, "no-repeat"); // 如果要繪製一個圓,使用下面程式碼 // context.arc(obj.width / 2, obj.height / 2, Math.max(obj.width, obj.height) / 2, 0, 2 * Math.PI); // 這裡使用圓角矩形 context.roundRect(0, 0, obj.width, obj.height, input.value * 1 || 0); // 填充繪製的圓 context.fillStyle = pattern; context.fill(); } image.src = "http://image.zhangxinxu.com/image/study/s/s256/mm1.jpg"; image.onload = function() { draw(this); }; input.addEventListener("change", function() { context.clearRect(0, 0, canvas.width, canvas.height); draw(image); }); </script> </body> </html>