1

I am trying to draw a shape using canvas and I am pretty close from what I want. Just the round corners are a bit hard to achieve what I need.

I have the following code

var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");

// Set rectangle and corner values
var cornerRadius = 5;

// Set faux rounded corners
context.lineJoin = "round";
context.lineWidth = 50;

context.beginPath();
context.moveTo(400, 60);
context.lineTo(360, 140);
context.lineTo(240, 135);
context.lineTo(180, 60);
context.closePath();
context.stroke();
context.fill();

which result in this shape here shape

What I am trying to achieve is having both left and right bottom corners rounded but not the top ones.

If I remove the lineJoin, then the rounded corners are gone.

So, how can I set the points where the lineJoin should run ?

Many thanks.

vbotio
  • 1,566
  • 3
  • 26
  • 53
  • Depending on what you are trying to do it may be easier to use the `context.drawImage` function. – luek baja Jul 15 '20 at 04:32
  • @luekbaja i don't think its an option for now as I intend to convert it into a reusable component in future. – vbotio Jul 15 '20 at 04:41
  • This answer shows how to add rounded corned https://stackoverflow.com/a/44856925/3877726 to any polygon, includes the code. – Blindman67 Jul 15 '20 at 05:13

1 Answers1

2

Check out using quadraticCurveTo that's what I used in this example here. Unfortunately you can't change the join type mid shape, however you have the ability to actually draw the path rounded instead.

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

canvas.width = canvas.height = 800;

// Set rectangle and corner values
const cornerRadius = 1;

ctx.lineWidth = 50;
ctx.beginPath();
ctx.moveTo(180, 60);
ctx.lineTo(400, 60);
ctx.quadraticCurveTo(400, 60, 400, 60);
ctx.lineTo(360, 140 - cornerRadius);
ctx.quadraticCurveTo(360, 140, 360 - cornerRadius, 140);
ctx.lineTo(240 + cornerRadius, 135);
ctx.quadraticCurveTo(240, 135, 240, 135 - cornerRadius);
ctx.lineTo(180, 60);
ctx.closePath();
ctx.stroke();
ctx.fill();
<canvas></canvas>
Loktar
  • 34,764
  • 7
  • 90
  • 104