Save images after using CSS filter

后端 未结 2 1613
臣服心动
臣服心动 2020-12-18 16:45

I\'m building a new website that will let users apply filters to images (just like Instagram). I will use -webkit-filter for that.

The user must be able

2条回答
  •  执笔经年
    2020-12-18 17:18

    There is no direct/straight forward method to export an image with CSS Filter.

    Follow the below steps for Saving/Exporting an Image with -webkit-filter applied on it:
    1. Render the image to a canvas:

    var canvas = document.createElement('canvas');
    canvas.id="canvasPhoto";
    canvas.width = imageContaainer.width;
    canvas.height = imageContaainer.height;
    var ctx = canvas.getContext('2d');
    ctx.drawImage(imageContaainer, 0, 0, canvas.width, canvas.height);
    
    1. Get the ImageData from canvas and apply the filter. Eg: I will apply grayscale filter to the ImageData below:

      function grayscale(ctx) {
      var pixels = ctx.getImageData(0,0,canvas.width, canvas.height);
      var d = pixels.data;
      for (var i=0; i
    2. Add an event and use the below code to trigger download

      function download(canvas) {
         var data = canvas.toDataURL("image/png");
         if (!window.open(data)) 
         {
             document.location.href = data;
         }
      }
      

提交回复
热议问题