0

I'm trying to crop an image to make it fit on my margin. One example of what I'm trying to achieve.

The original image:

The original image

After the crop:

After the crop

I already managed to crop the rectagle, but I have no idea how I can remove the corners. I tried with ctx.arc(), but I'm kinda confused with the values that I should use for x, y, radius and angle. The border-radius that I'm using depends on the screen size, but I've the value.

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
lcsxx
  • 1
  • Please read [ask], then [edit] with a [mcve]. Take a [tour] if you missed it. – Roko C. Buljan Jul 21 '22 at 21:32
  • There is now a `roundRect` method in the specs, available in Chrome and for which I made [a polyfill](https://github.com/Kaiido/roundRect). – Kaiido Jul 22 '22 at 00:25

1 Answers1

0

Use clip() with a Path2D and arcTo(). You will have to figure out your specific values which can be done with a little math (or trial and error). Be sure to draw you image after you clip()

arcTo()

clip()

let canvas = document.getElementById('canvas')
let ctx = canvas.getContext('2d')
canvas.width = 400;
canvas.height = 400;

let border = new Path2D();
border.arcTo(canvas.width, 0, canvas.width, 20, 50);
border.arcTo(canvas.width, canvas.height, 0, canvas.height, 50);
border.arcTo(0, canvas.height, 0, 20, 50);
border.arcTo(0, 0, 20, 0, 50);
ctx.clip(border);


function draw() {
  ctx.fillStyle = 'green';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
}
draw()
<canvas id="canvas"></canvas>
Justin
  • 2,873
  • 3
  • 9
  • 16