Dan
Dan

Reputation: 517

Add border to ctx.drawImage() within canvas HTML5

I'm making a demotivational meme generator and need to add a white border to the image added within the canvas

ctx.drawImage(img, 0, 0, imgWidth, imgHeight, 20, 20,300,300);

this is to add a border to the canvas

ctx.strokeStyle = 'red';
ctx.lineWidth = 2;

ctx.strokeRect(0, 0, theCanvas.width, theCanvas.height);

how do I add a border to the image inside?

those are the coordinates:

     ctx.drawImage(img, 0, 0, imgWidth,imgHeight, (canvas.width - newImgWidth) / 2, 20,newImgWidth,newImgHeight);

     newImgWidth,newImgHeight > 80% of imgWidth,imgHeight

black outline within a white border around the image

Upvotes: 0

Views: 1429

Answers (1)

kshetline
kshetline

Reputation: 13682

Try this:

ctx.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height - 2);

You're using a line that's two pixels wide. You have to account for the thickness of the line in the rectangle you specify. You might expect the line thickness to all go towards the inside of the rectangle (and that would be convenient a lot of the time), but the thickness of the line is evenly split around both sides of the 0-thickness mathematical perimeter of the specified rectangle.

Upvotes: 1

Related Questions