Sadie LaBounty
Sadie LaBounty

Reputation: 379

Javascript - Function to Plot Curved Rectangle

I'm trying to write a function that draws a curved rectangle with given xy coordinates, width and height within an html canvas but my script currently outputs a blank canvas. Why is the code not drawing the rectangle?

var c=document.getElementById(id);
var ctx=c.getContext('2d');

function makeCurvedRect(x, y, w, h) {
    ctx.beginPath();
    ctx.moveTo(x+10, y);
    ctx.lineTo(x+w-10, y);
    ctx.quadraticCurveTo(x+w, y, x+w, y+10);
    ctx.lineTo(x+w, y+h-10);
    ctx.quadraticCurveTo(x+w, y+h, x+w-10, y+h);
    ctx.lineTo(x+10, y+h);
    ctx.quadraticCurveTo(x, y+h, x, y+h - 10]);
    ctx.lineTo(x, y+10);
    ctx.quadraticCurveTo(x, y, x+10, y);
    ctx.stroke();
}

makeCurvedRect(162.5,40,175,175);

Upvotes: 0

Views: 121

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

It's because, you have an unnecessary square bracket (]) at this line

ctx.quadraticCurveTo(x, y+h, x, y+h - 10]);
                                        ^ this

which causes the code to break

var c = document.getElementById('canvas');
var ctx = c.getContext('2d');

function makeCurvedRect(x, y, w, h) {
    ctx.beginPath();
    ctx.moveTo(x + 10, y);
    ctx.lineTo(x + w - 10, y);
    ctx.quadraticCurveTo(x + w, y, x + w, y + 10);
    ctx.lineTo(x + w, y + h - 10);
    ctx.quadraticCurveTo(x + w, y + h, x + w - 10, y + h);
    ctx.lineTo(x + 10, y + h);
    ctx.quadraticCurveTo(x, y + h, x, y + h - 10);
    ctx.lineTo(x, y + 10);
    ctx.quadraticCurveTo(x, y, x + 10, y);
    ctx.stroke();
}
makeCurvedRect(60, 60, 175, 175);
canvas {
  border: 1px solid black;
}
<canvas id="canvas" width="300" height="300"></canvas>

Upvotes: 2

Related Questions