使用 arcTo 方法
by G Issac
HTML
<div>
<img src="https://pbs.twimg.com/profile_images/588883654157291520/4DBMn6_A.jpg">
</div>
<canvas id="canvas" width="240" height="240"></canvas>
<canvas id="canvas1" width="480" height="240"></canvas>
CSS
img{
margin: 50px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
#canvas{
border: 1px solid gray;margin-left: 50px;display: inline-block;
}
#canvas1{ border: 1px solid gray;margin-left: 350px;display: inline-block; }
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.arcTo(x, y + h, x, y, r);
this.arcTo(x, y, x + w, y, r);
this.closePath();
return this;
}
var canvas = document.querySelector("#canvas");
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'https://pbs.twimg.com/profile_images/588883654157291520/4DBMn6_A.jpg';
var pattern = context.createPattern(img, "no-repeat");
context.roundRect(0, 0, img.width, img.height, 1000);
context.fillStyle = pattern;
context.fill();
var canvas1 = document.querySelector("#canvas1");
var context1 = canvas1.getContext("2d");
var pattern1 = context1.createPattern(img, "no-repeat");
context1.roundRect(50, 0, img.width, img.height, 1000);
context1.fillStyle = pattern1;
context1.fill();