function drawLine(ctx, sX, sY, eX, eY, sRGB, fRGB, lWidth, capStyle)
{
ctx.beginPath();
ctx.moveTo(sX, sY);
ctx.lineTo(eX, eY);
ctx.lineWidth = lWidth||5;
ctx.strokeStyle = 'rgb(49, 129, 48)';
ctx.lineCap = 'round';
ctx.stroke();
ctx.closePath();
}
And then I want to call the function like this:
drawLine(ctx, 50, 50, 100, 100, someStrokeStyle, someFillStyle, someCapStyle);
As you can see I have skipped the lWidth
parameter. I want the function to still work, even when the lWidth
is not passed as a parameter. How will I do this? Atm, it might think that the someCapStyle
is the lwidth
.
When you have a big amount of arguments to pass into a function like you have, use an object:
function foo({param1: val1, parma2: val2}) {}
In that case you wont be depend on number of arguments and order of them being represented.
So you can rewrite your function:
function drawLine(drawObj)
{
ctx.beginPath();
ctx.moveTo(drawObj.sX, drawObj.sY);
ctx.lineTo(drawObj.eX, drawObj.eY);
ctx.lineWidth = drawObj.lWidth||5;
ctx.strokeStyle = drawObj.sRGB;
ctx.lineCap = drawObj.capStyle;
ctx.stroke();
ctx.closePath();
}
When you don't pass any argument, undefined
value is passed instead, so just check in the function whether the argument has been passed or not:
if(typeof argument == "undefined")
{
argument = "default value";
}
So to not pass lWidth
, just pass undefined
as its value
P.S. the best way is to use a single argument args
, which will be object containing all current parameters as properties.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With