How to save rounded corner Image using todataUrl?

1.2k Views Asked by At

I need to save images drawn (from base64 encoding) into a rounded corner canvas. The canvas is defined using:

<canvas id="thumbnailImage" width="86" height="86" style="border:1px solid #d3d3d3;border-radius:10px;">

The image appears as expected (using ctx.drawImage etc...), with rounded corners. Then I obtain the base64 encoding data of the rounded image using

        var imageData = $(jImageId)[0].toDataURL("image/jpeg",qly);

Unfortunately, when the image is displayed without a rounded-corner canvas, the corners are still there...

Question: is there a simple way to get the base64 image data, as it appears on the canvas, or do I have to go through the painful pixel clipping ordeal ?

thank you !

1

There are 1 best solutions below

0
On BEST ANSWER

It seems border radius is just the styling of HTML, not image data inside canvas, so you'll have to erase the corner away to get the rounded image.

After searching I found these posts which taught me how to erase shape instead of just retangle, so here we go:

JSFiddle (Although it won't work on the final export part due to COR restriction)

ctx.drawImage(src,0,0);
ctx.save();
ctx.globalCompositeOperation="destination-out";
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(10,0);
ctx.arcTo(0,0,0,10,10);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(100,0);
ctx.lineTo(90,0);
ctx.arcTo(100,0,100,10,10);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(0,90);
ctx.arcTo(0,100,10,100,10);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(100,100);
ctx.lineTo(90,100);
ctx.arcTo(100,100,100,90,10);
ctx.closePath();
ctx.fill();
ctx.restore();
des.src=can.toDataURL("image/png");

Base on the fact that you already know the radius of the rounded corner.

Here's a screenshot of the result on my localhost:

localhost result