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();
运行出来结果