canvas繪製三角形

admin發表於2017-02-17

分享一段程式碼例項,它實現了利用canvas繪製三角形的功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="cvs" width="500" height="500"></canvas>
<script>
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
 
/*
* 封裝一個畫等腰三角形的函式
* */
// 等腰三角形類
function SJX(x, y, w, h) {
  this.x = x;
  this.y = y;
  this.w = w;
  this.h = h;
}
// 給SJX類原型擴充一個繪製方法
SJX.prototype = {
  draw: function () {
    ctx.moveTo(this.x, this.y);
    ctx.lineTo(this.x + this.w / 2, this.y + this.h);
    ctx.lineTo(this.x - this.w / 2, this.y + this.h);
    ctx.lineTo(this.x, this.y);
    ctx.stroke();
  }
};
var sjx1 = new SJX(50, 50, 100, 50);
var sjx2 = new SJX(200, 50, 50, 80);
var sjx3 = new SJX(300, 50, 60, 60);
sjx1.draw();
sjx2.draw();
sjx3.draw();
</script>
</body>
</html>

相關文章