封装一个构造函数 绘制矩形

<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>封装 构造函数 绘制矩形</title>
	<style>
		html{
			overflow:hidden;
		}
	</style>
</head>
<body>
	<canvas id="myCanvas"></canvas>
	<script>
		//构造函数
		function Rect(options){
			this.init(options);
		}
		Rect.prototype={
			init:function(options){
				options=options||{};
				this.x=options.x||0;
				this.y=options.y||0;
				this.width=options.width||100;
				this.height=options.height ||100;
				this.stroke=options.stroke ||"#000";
				this.strokeWidth=options.strokeWidth||2;
				this.fill=options.fill||"transparent";
				this.rotate=options.rotate ||0;
				this.scaleX=options.scaleX || 1;
				this.scaleY=options.scaleY ||1;
				this.offsetX=options.offsetX || 0;
				this.offsetY=options.offsetY ||0;
			},
			render:function(ctx){
				ctx.save();
				ctx.translate(this.x,this.y);
				ctx.rotate(this.rotate);
				ctx.scale(this.scaleX,this.scaleY);
				ctx.beginPath();
				ctx.rect(this.offsetX,this.offsetY,this.width,this.height);
				ctx.fillStyle=this.fill;
				ctx.strokeStyle=this.stroke;
				ctx.lineWidth=this.strokeWidth;
				ctx.fill();
				ctx.stroke();
				ctx.restore();
			}
		}

		var canvas=document.getElementById("myCanvas");
		canvas.width=window.innerWidth;
		canvas.height=window.innerHeight;
		var ctx=canvas.getContext("2d");
		var rect=new Rect({
			x:300,
			y:300,
			width:200,
			height:200,
			fill:"skyblue",
			stroke:"pink",
			rotate:0,
			offsetX:-100,
			offsetY:-100
		});
		rect.render(ctx);
		var angle=0;
		setInterval(function(){
			canvas.width=canvas.width;
			rect.rotate=angle;
			rect.render(ctx);
			angle+=Math.PI/12;
		},100)
	</script>
</body>
</html>
posted @ 2017-11-21 19:04  不完美的完美  阅读(387)  评论(0编辑  收藏  举报