您的位置:首页 - 教程 - HTML5 - 正文
html5 canvas 绘制圆角矩形
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);
}

//----------------------------------------

评论: