canvas 繪制圓角矩形(僅邊框)
HTML
<canvas id="canvasBox" width="150" height="50"></canvas>
JS
var canvas,ctx3,canvasWidth,canvasHeight; function canvasBox(){ canvas=document.getElementById('canvasBox'); ctx3=canvas.getContext('2d'); canvasWidth=canvas.width; canvasHeight=canvas.height; juxing(ctx3,0,0,canvasWidth,canvasHeight,20); } canvasBox(); function juxing(ctx3,x,y,width,height,radius){ ctx3.beginPath(); //開始繪制路徑 ctx3.lineWidth = 5; //邊框大小 // 起始點:moveTo(x,y) 二次貝塞爾曲線:quadraticCurveTo('控制點x','控制點y','結束點x','結束點y') 結束點:lineTo(x,y) ; ctx3.moveTo(x+radius,y); ctx3.lineTo(x+width-radius,y); ctx3.quadraticCurveTo(x+width, y, x+width, y+radius); ctx3.lineTo(x+width,y+height-radius); ctx3.quadraticCurveTo(x+width, y+height, x+width-radius, y+height); ctx3.lineTo(x+radius,y+height); ctx3.quadraticCurveTo(x, y+height, x, y+height-radius); ctx3.lineTo(x,y+radius); ctx3.quadraticCurveTo(x, y, x+radius, y); ctx3.fillStyle ="#999"; //為圓角矩形填充顏色 ctx3.strokeStyle="green"; //矩形邊框顏色 ctx3.closePath(); //閉合繪制的路徑 ctx3.fill(); //填充當前的路徑,默認顏色是黑色 ctx3.stroke(); //繪制確切的路徑 }
運行結果
如果不需要填充顏色,只需把以下代碼去掉即可
ctx3.fillStyle="#999" ctx3.fill();
運行出來結果