内容整理承接:
《数据可视化基础 - canvas进阶篇(四):线条样式》
4.1封装常用的绘制函数
4.1.1封装一个矩形
思考:我们用到的矩形需要哪些绘制的东西呢?
1、矩形的 x、y坐标
2、矩形的宽高
3、矩形的边框的线条样式、线条宽度
4、矩形填充的样式
5、矩形的旋转角度
6、矩形的缩小放大
下面是把上面所有的功能进行封装的代码:
1 function ItcastRect( option ) {//矩形构造函数
2 this._init(option);
3 }
4 ItcastRect.prototype = { //矩形的原型对象
5 _init: function( option ) { //初始化方法
6 option = option || {};
7 this.x = option.x === 0 ? 0 : option.x || 100;
8 this.y = option.y === 0 ? 0 : option.y || 100;
9 this.w = option.w || 100;
10 this.h = option.h || 100;
11 this.angle = option.angle === 0 ? 0 : option.angle || 0;
12 this.fillStyle = option.fillStyle || 'silver';
13 this.strokeStyle = option.strokeStyle || 'red';
14 this.strokeWidth = option.strokeWidth || 4;
15 this.scaleX = option.scaleX || 1;
16 this.scaleY = option.Y || 1;
17 },
18 render: function( ctx ) {//把矩形渲染到canvas中
19 ctx.save();
20 ctx.translate( this.x, this.y );//位移画布
21 ctx.rotate( this.angle * Math.PI / 180 );//旋转角度
22 ctx.scale( this.scaleX, this.scaleY );//缩放
23 ctx.fillStyle = this.fillStyle;
24 ctx.fillRect( 0, 0, this.w, this.h ); //填充矩形
25 ctx.lineWidth = this.strokeWidth; //线宽
26 ctx.strokeStyle = this.strokeStyle; //填充样式
27 ctx.strokeRect( 0,0,this.w,this.h ); //描边样式
28 ctx.restore();
29 },
30 constructor: ItcastRect
31 };
复制
4.1.2 封装圆形代码
封装圆形的代码如下:
1 function ItcastCircle( option ) {
2 this._init( option );
3 }
4 ItcastCircle.prototype = {
5 _init: function( option ) {
6 option = option || {};
7 this.x = option.x === 0 ? 0 : option.x || 100;
8 this.y = option.y === 0 ? 0 : option.y || 100;
9 this.w = option.w || 100;
10 this.h = option.h || 100;
11 this.angle = option.angle === 0 ? 0 : option.angle || 0;
12 this.fillStyle = option.fillStyle || 'silver';
13 this.strokeStyle = option.strokeStyle || 'red';
14 this.strokeWidth = option.strokeWidth || 4;
15 this.scaleX = option.scaleX || 1;
16 this.scaleY = option.Y || 1;
17 this.opactity = option.opactity || 1;
18 this.counterclockwise =
19 option.counterclockwise === true ? true : option.counterclockwise || false;
20 this.startAngle = option.startAngle == 0 ? 0 : option.startAngle || 0;
21 this.endAngle = option.endAngle == 0 ? 0 : option.endAngle || 0;
22 this.startAngle = this.startAngle * Math.PI/180;
23 this.endAngle = this.endAngle * Math.PI / 180;
24 this.r = option.r || 100;
25 },
26 render: function( ctx ) {
27 ctx.save();
28 ctx.translate( this.x, this.y);
29 ctx.scale( this.scaleX, this.scaleY );
30 ctx.rotate( this.agnle * Math.PI / 180 );
31 ctx.globalAlpha = this.opacity;
32 ctx.fillStyle = this.fillStyle;
33 ctx.strokeStyle = this.strokeStyle;
34 ctx.moveTo(0, 0);
35 ctx.arc( 0, 0, this.r, this.startAngle, this.endAngle, this.counterclockwise);
36 ctx.fill();
37 ctx.stroke();
38 ctx.restore();
39 },
40 constructor: ItcastCircle
41 };