canvas画边框不一样的矩形

需求:用canvas画一个边框样式不一样的矩形

方法一:简单粗暴,直接用canvas填充矩形,给canvas标签设置样式即可。(推荐)

<!DOCTYPE html >
< html >
< head >
< title >canvas画边框不一样的长方形 </ title >
< style >
.canvas {
border-top: 5px solid #aaa;
border-right: 10px solid red;
border-bottom: 10px solid blue;
border-left: 20px solid black;
display: block;
margin: 50 auto;
}
< / style >
</ head >

< body >
< canvas id= "canvas" class= "canvas" width= "400" height= "300" ></ canvas >
< script >
var canvas = document. getElementById( "canvas");
var ctx = canvas. getContext( "2d");
ctx. fillStyle = 'pink';
ctx. fillRect( 0, 0, 400, 300);
< / script >
</ body >

</ html >

效果如下:


方法二:一条线一条线的画边框,再填充,此方法比较麻烦,且ctx.lineWidth较大时,有瑕疵

<!DOCTYPE html >
< html lang= "en" >

< head >
< meta charset= "UTF-8" >
< meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
< meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
< title >cancas画边框样式不一样的矩形 </ title >
</ head >

< body >
< canvas id= "canvas" width= "200" height= "200" ></ canvas >
< script >
var canvas = document. getElementById( 'canvas');
var ctx = canvas. getContext( '2d');
//左边框
ctx. beginPath();
ctx. moveTo( 10, 10);
ctx. lineTo( 10, 180);
ctx. closePath(); //闭合路径
ctx. lineWidth = 1; //线的边框为10像素
ctx. strokeStyle = 'blue';
ctx. stroke(); //绘制定义的图形

//下边框
ctx. beginPath();
ctx. moveTo( 10, 180);
ctx. lineTo( 180, 180);
ctx. closePath(); //闭合路径
ctx. lineWidth = 1; //线的边框为10像素
ctx. strokeStyle = 'green';
ctx. stroke(); //绘制定义的图形

//右边框
ctx. beginPath();
ctx. moveTo( 180, 180);
ctx. lineTo( 180, 10);
ctx. closePath(); //闭合路径
ctx. lineWidth = 1; //线的边框为10像素
ctx. strokeStyle = 'red';
ctx. stroke(); //绘制定义的图形


//上边框
ctx. beginPath();
ctx. moveTo( 180, 10);
ctx. lineTo( 10, 10);
ctx. closePath(); //闭合路径
ctx. lineWidth = 1; //线的边框为10像素
ctx. strokeStyle = 'black';
ctx. stroke(); //绘制定义的图形

ctx. rect( 10, 10, 170, 170);
ctx. fillStyle = "pink";
ctx. fill();
< / script >
</ body >

</ html >

效果如下:


猜你喜欢

转载自blog.csdn.net/xiaoxiaoluckylucky/article/details/80938726