Home > OS >  Fading Canvas from Opacity 1 to 0 on Edges
Fading Canvas from Opacity 1 to 0 on Edges

Time:05-17

I am creating a Canvas with an image inside using

context.drawImage(image, (cWidth - iRatio)/2, 0, iRatio, cHeight);

And behind the canvas there is a Blue Wallpaper inside a Div.

Canvas

As you can see on the image (done on Photoshop), the Canvas (Image with the Sun) is fading from opacity 1 to 0.

How can I do it in Canvas with JS or CSS ? I want the Canvas edges(All, so Left, Right, Top and botoom) to have an opacity 0 and fading to center with opacity 1.

CodePudding user response:

You can use mask:

img {
  mask:radial-gradient(circle, white 30%, transparent 60%);
}
<img src="https://i.stack.imgur.com/Onn3y.png" />

MDN has many example - you can use gradients, svg, and even pngs to get the effect you want.

There's also mask-border but it isn't as well supported (for example, Firefox doesn't support it yet).

CodePudding user response:

Using filter

Use ctx.filter to create a blur and use that blur to keep pixels you want and remove pixels from edge using ctx.globalCompoiteOperation = "detination-in"

Example below uses function featherEdge feather edges of canvas content.

const ctx = canvas.getContext("2d");
const img = new Image;
img.src = "https://i.stack.imgur.com/Onn3y.png";
img.addEventListener("load", draw, {once: true});
function draw() {    
    ctx.drawImage(img, 0, 0);
    featherEdge(20, 2);
}

function featherEdge(blurRadius, inset) {
    ctx.filter = "blur("   blurRadius   "px)";
    ctx.globalCompositeOperation = "destination-in";
    const inBy = blurRadius   inset;
    ctx.fillRect(inBy, inBy, canvas.width - inBy * 2, canvas.height - inBy * 2);
}
canvas {
   background: cyan;
}
<canvas id="canvas" width="200" height="200"></canvas>

  • Related