效果圖: ...
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>用面向對象的思想 封裝 在canvas繪製直線的函數</title> 6 </head> 7 <body> 8 <canvas id="cv"></canvas> 9 </body> 10 </html> 11 <script> 12 var cv = document.getElementById("cv"); 13 cv.width = 600; 14 cv.height = 300; 15 cv.style.border = "1px solid red"; 16 var ctx = cv.getContext("2d"); 17 18 //面向對象編程 19 //1 創建構造函數 20 //2 構造函數的原型設置 21 //3 調用的時候,通過 new+構造函數 來創建一個對象(實例) 22 23 //構造繪製直線的函數 24 function drawLine(parameters) { 25 this.init(parameters); 26 } 27 //替換原型對象實現繼承 28 drawLine.prototype = { 29 constructor: drawLine, 30 init: function (parameters) { 31 this.ctx = parameters.ctx; 32 this.startX = parameters.points[0]; 33 this.startY = parameters.points[1]; 34 this.endX = parameters.points[2]; 35 this.endY = parameters.points[3]; 36 //以下3個屬性,可以不設置,用短路運算實現添加預設屬性值 37 this.lineWidth = parameters.lineWidth || 1; 38 this.lineDash = parameters.lineDash || []; 39 this.strokeStyle = parameters.strokeStyle || "#000"; 40 }, 41 //原型中,一般用來儲存對象的方法或者共有的屬性 42 stroke: function () { 43 this.ctx.beginPath(); 44 this.ctx.moveTo(this.startX, this.startY); 45 this.ctx.lineTo(this.endX, this.endY); 46 this.ctx.lineWidth = this.lineWidth; 47 this.ctx.setLineDash(this.lineDash); 48 this.ctx.strokeStyle = this.strokeStyle; 49 this.ctx.stroke(); 50 } 51 }; 52 53 //調用構造函數,傳入參數 54 var line = new drawLine({ 55 ctx: ctx, 56 points: [100, 100, 300, 100], 57 lineDash: [4, 2], 58 strokeStyle: "red" 59 }); 60 line.stroke(); 61 var line2 = new drawLine({ 62 ctx: ctx, 63 points: [100, 200, 300, 200], 64 lineWidth: 6 65 }); 66 line2.stroke(); 67 </script>
效果圖: