利用canvas封裝一個繪製矩形的函數

在需要使用矩形時,引入tjRect.js文件:

function tjRect(option){
	this._init(option);
}
tjRect.prototype = {
	_init:function(option){
		this.x = option.x || 0; //矩形左上角的 x 座標
		this.y = option.y || 0;
		this.width = option.width || 0; //矩形的寬度
		this.height = option.height || 0;
		this.fillStyle = option.fillStyle || "red";
		this.strokeStyle = option.strokeStyle || "red";
		this.lineWidth = option.lineWidth || 1; //矩形描邊的寬度
		this.scaleX = option.scaleX || 1;
		this.scaleY = option.scaleY || 1;
		this.rotation = option.rotation || 0; //旋轉角度
	},
	render:function(ctx){
		ctx.save();

		ctx.beginPath();
		ctx.lineWidth = this.lineWidth;
		ctx.scale(this.scaleX, this.scaleY);
		ctx.rotate(this.rotation*Math.PI/180);
		ctx.rect(this.x, this.y, this.width, this.height);
		ctx.fillStyle = this.fillStyle; 
		ctx.fill();
		ctx.strokeStyle = this.strokeStyle;
		ctx.stroke();

		ctx.restore();
	}
}

 html頁面中的代碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="tjJs/tjRect.js"></script>
</head>
<body>
	<canvas id="canvas">
		您的瀏覽器不支持canvas,請升級您的瀏覽器
	</canvas>
	<script>
		var canvas = document.getElementById("canvas");
		var ctx = canvas.getContext("2d");
		canvas.width = 600;
		canvas.height = 600;
		canvas.style.border = "1px solid black";

		var rect = new tjRect({  //根據需要設置參數
			x:100,
			y:100,
			width:90,
			height:100,
			fillStyle:"green",
			strokeStyle:"orange",
			lineWidth:2,
			rotation:18,
			scaleX:1.2,
			scaleY:1.5
		});
		rect.render(ctx);

	</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章