Capture/save/export an image with CSS filter effects applied

前端 未结 2 1668
星月不相逢
星月不相逢 2020-12-10 02:37

I\'m tooling around to make a simple picture editor that uses CSS3 filter effects (saturation, sepia, contrast, etc.)

Making the picture editor is the easy part, how

相关标签:
2条回答
  • 2020-12-10 02:53

    I got your answer. I made this program, finally it's work.

    those step is :
    1. upload the image (JPG/PNG)
    2. convert to canvas
    3. custom with css filters.
    4. render using camanJS to save as image.
    5. done.

    you also can reset effect value by modifying value of filters to its default.

    good luck!

    0 讨论(0)
  • 2020-12-10 02:58

    You're not, that I'm aware of, able to apply CSS to graphics in the HTML5 canvas element (as they're not a part of the DOM).

    However, that's OK! We can still do basic filter effects relatively easy and save them out as an image with just a few lines of JavaScript.

    I found a good article that goes over applying a sepia-like effect to the canvas and saving it as an image. Rather than copying it, I'll highlight the larger takeaways from the article.

    Modifying the canvas image:

    var canvas = document.getElementById('canvasElementId'),
        context = canvas.getContext('2d');
    
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
    
    for (var i = 0; i < imageData.data.length; i+=4) {
        ...
    }
    

    In order to get access to some canvas API, you'll need to activate the 2d context on the canvas using the above JavaScript. MDN has some great documentation on the API that is available to you with the context object, but the important part to note here is the getImageData() call. Basically, it will grab all the pixel values in the area that you defined (in the case above, we're grabbing the whole image). Then, with this data in hand, we can iterate through all the pixels and change them as needed. In the sepia article, it's obviously making some interesting adjustments, but you can also do grayscale, blurring, or any other changes as necessary and there's an awesome canvas filters library on Github for just that.

    How to save the canvas image:

    var canvas = document.getElementById('canvasElementId'),
        image = document.createElement("img");
    
    image.src = canvas.toDataURL('image/jpeg');
    
    document.body.appendChild(image);
    

    The above script will select your canvas (assuming you've already done your drawings) and create an image element. It them uses toDataURL() to generate a url that you can use to set the source on an image element. In the example above, the image element is appended to the document body. You can view more info on MDN's canvas page.

    0 讨论(0)
提交回复
热议问题