How to Save an HTML Element With Filters to an Image?


The visual effect of an element is controlled by the filter property. The majority of the time, this attribute is utilized in image content to change the rendering, backdrop, border, etc. of the image. Following is the syntax for filter property -

filter: none|blur()|brightness()|contrast()|drop-shadow()|
grayscale()|hue-rotate()|invert()|opacity()|saturate()|sepia()|
url();

let’s dive into the article for getting better understanding on saving an HTML element with filters to an image.

Saving HTML element with filters to image

An image can be included in an HTML page using the <img> tag. Images are linked to online pages; they are not actually placed into web pages. The relevant picture is held in place by the <img> tag. The <image> tag must have the following two attributes −

  • src

  • alt

Syntax

Following is the syntax for <img> tag -

<img src="" alt="" width="" height="">

Let’s look into the following examples for getting more idea on saving an HTML element with filters to image.

Example

In the following we are using running the script to save the HTML element with filter to image.

<!DOCTYPE HTML>
<html>
   <body>
      <style>
         img {
            width: 400px;
            height: 400px;
         }
      </style>
      <img src="https://www.tutorialspoint.com/java/images/java-mini-logo.jpg" id="tutorial1" />
      <canvas id="tutorial" width="400px" height="400px"></canvas>
      <a id="tutorial2">Click To Download</a>
      <script>
         var canvas = document.getElementById('tutorial');
         var ctx = canvas.getContext('2d');
         ctx.filter = "sepia(80%)";
         var img = document.getElementById("tutorial1");
         ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
         var downloadFile = document.getElementById('tutorial2');
         downloadFile.addEventListener('click', download, false);
         function download() {
            var dt = canvas.toDataURL('image/jpeg');
            this.href = dt;
         };
      </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of an image uploaded on the webpage along with an image with applied effects obtained from the original image and text. When the user clicks "download," the effects used are saved.

Updated on: 20-Apr-2023

580 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements