在需要使用矩形時,引入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>