Search code examples
javascriptimagehtml5-canvas

Creating a blurred image in javascrpt


I want to generate a blurred image from a normal image. I've searched on the internet and found out that people have done it by putting CSS filter property through javascript on Image to make it blur. But it can be removed by inspecting the page and I don't want that.

I want to generate a blurred version of image through javascript. I think I can do it with canvas but I never worked with canvas and any help will be highly appreciated (:


Solution

  • Simple filters

    You can apply a blur via the canvas using ctx.filter. CanvasRenderingContext2D.filter will accept a (limited set of) filters defined as strings. Eg ctx.filter = "blur(10px)";

    See ctx.filter for set of filters you can use directly.

    Example

    Example uses CanvasRenderingContext2D.filter to blur image over time.

    const img = new Image;
    img.src = "https://i.sstatic.net/C7qq2.png?s=256&g=1";
    img.addEventListener("load", () => requestAnimationFrame(uodate));
    function drawImageBlur(img, blurAmount) {
       const ctx = can.getContext("2d");
       ctx.clearRect(0,0,128,128);
       ctx.filter = "blur(" + blurAmount+ "px)";
       ctx.drawImage(img, 128 - img.naturalWidth * 0.5, 128 - img.naturalHeight * 0.5);
    }
    var frameCount = 0;
    function uodate(time) {
      if (frameCount++ % 10 === 0) {  // no point burning CPU cycles so only once every 10 frames
          drawImageBlur(img, Math.sin(time / 1000) * 5 + 6);
      }
      requestAnimationFrame(uodate);
    }
    canvas {border: 1px solid black;}
    <canvas id="can" width="256"  height="256"></canvas>

    There is no way to protect the image from inspection if you apply the image blur on the client (no matter what method you use). If you want to obfuscate (blur) the image it must be done on the server.