html5沒有圓角矩形的繪制函數,不過可以通過arc和line組合成圓角矩形,或者quadraticCurveTo和lineTo組合成圓角矩形。
下面是示例代碼:
//-------------------------------------
/**
* 繪制圓角矩形,用arc和LineTo函數
*/
function roundRectanglePath(context,rect,radius)
{
context.beginPath();
context.moveTo( rect.getX()+radius,rect.getY() );
context.lineTo( rect.getRight()-radius,rect.getY() );
context.arc( rect.getRight()-radius,rect.getY()+radius, radius, 3*Math.PI/2,2*Math.PI, false);
context.lineTo( rect.getRight(),rect.getBottom()-radius);
context.arc( rect.getRight()-radius,rect.getBottom()-radius, radius, 0, Math.PI/2, false);
context.lineTo( rect.getX()+radius,rect.getBottom() );
context.arc( rect.getX()+radius,rect.getBottom()-radius, radius, Math.PI/2, Math.PI, false);
context.lineTo( rect.getX(),rect.getY()+radius);
context.arc( rect.getX()+radius,rect.getY()+radius, radius,Math.PI, 3*Math.PI/2, false);
context.closePath();
}
/**
* 繪制圓角矩形,用quadraticCurveTo和lineTo函數
*/
function roundRectanglePath2(context,rect,radius)
{
context.beginPath();
context.moveTo( rect.getX()+radius,rect.getY() );
context.lineTo( rect.getRight()-radius,rect.getY() );
context.quadraticCurveTo( rect.getRight(), rect.getY(), rect.getRight(), rect.getY() + radius);
context.lineTo( rect.getRight(),rect.getBottom()-radius);
context.quadraticCurveTo( rect.getRight(), rect.getBottom(), rect.getRight()-radius, rect.getBottom());
context.lineTo( rect.getX()+radius,rect.getBottom() );
context.quadraticCurveTo( rect.getX(), rect.getBottom(), rect.getX(), rect.getBottom()-radius);
context.lineTo( rect.getX(),rect.getY()+radius);
context.quadraticCurveTo( rect.getX(), rect.getY(), rect.getX()+radius, rect.getY());
context.closePath();
}
//這是兩個函數用到的矩形對象------------------------------------
function Rect(x,y,width,height)
{
this.x = x;
this.y = y;
this.width = width;
this.height= height;
}
Rect.prototype.getX = function()
{
return this.x;
}
Rect.prototype.getY = function()
{
return this.y;
}
Rect.prototype.getWidth = function()
{
return this.width;
}
Rect.prototype.getHeight = function()
{
return this.height;
}
Rect.prototype.getLeft = function()
{
return this.x;
}
Rect.prototype.getTop = function()
{
return this.y;
}
Rect.prototype.getRight = function()
{
return (this.x + this.width);
}
Rect.prototype.getBottom = function()
{
return (this.y + this.height);
}
//----------------------------------------