你快到了!
只需将填充和描边定义添加到您的矩形对象:
var rect1 = {
x: 125,
y: 10,
w: 20,
h: 20,
fill:'lightgray',
stroke:'skyblue',
};
然后你可以使用一个函数来绘制每个矩形:
drawRect(rect1);
function drawRect(rect){
ctx.fillStyle=rect.fill;
ctx.strokeStyle=rect.stroke;
ctx.fillRect(rect.x,rect.y,rect.w,rect.h);
ctx.strokeRect(rect.x,rect.y,rect.w,rect.h);
}
你甚至可以创建一个“工厂”函数,用你给定的定义创建一个新的矩形:
var grayRect=createRect(125,10,20,20,'lightgray','skyblue');
var redRect=createRect(120,110,10,10,'red','skyblue');
function createRect(x,y,width,height,fill,stroke){
return({
x:x,
y:y,
w:width,
h:height,
fill:fill,
stroke:stroke
});
}
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var grayRect=createRect(125,10,20,20,'lightgray','skyblue');
var redRect=createRect(120,110,10,10,'red','skyblue');
drawRect(grayRect);
drawRect(redRect);
function createRect(x,y,width,height,fill,stroke){
return({
x:x,y:y,
width:width,height:height,
fill:fill,stroke:stroke
});
}
function drawRect(rect){
ctx.fillStyle=rect.fill;
ctx.strokeStyle=rect.stroke;
ctx.fillRect(rect.x,rect.y,rect.width,rect.height);
ctx.strokeRect(rect.x,rect.y,rect.width,rect.height);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>