Canvas Projects – CodingNepal https://www.codingnepalweb.com CodingNepal is a blog dedicated to providing valuable and informative content about web development technologies such as HTML, CSS, JavaScript, and PHP. Thu, 11 May 2023 07:45:30 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 How to Take Simple Screenshot in Vanilla JavaScript https://www.codingnepalweb.com/how-to-take-screenshot-vanilla-javascript/ https://www.codingnepalweb.com/how-to-take-screenshot-vanilla-javascript/#comments Tue, 29 Nov 2022 19:12:33 +0000 https://www.codingnepalweb.com/?p=3488 How to Take Screenshots in Vanilla JavaScript

Did you know you can take or capture screenshots of any window using vanilla JavaScript? Yes, there’s no need for an external library or plugin to take a simple screenshot of the web page or window.

If you don’t know, I previously shared a blog on How to Take Screenshots using JavaScript HTML2Canvas. HTML2Canvas is a JavaScript library for taking screenshots of entire or parts of a webpage.

However, in this blog, you will learn to do the same thing (capturing screenshots) with plain JavaScript. The codes and logic behind taking a screenshot are so easy that you can easily understand them if you have some basic JavaScript knowledge.

To take a screenshot, I’ve created a dummy web page with some headings, paragraphs, and a button. When the user clicks on the button, a prompt window will be shown asking for permission to capture a screenshot. If the user accepts the permission, the webpage will be screenshotted and shown as an image lightbox.

If you’re excited to know how these actually look, you can watch the given YouTube video on How to Take Screenshots in JavaScript.

Video Tutorial of Taking Screenshot in JavaScript

I hope you liked the demo of Taking Screenshots and understood how I created it using vanilla JavaScript. I’ve shown the screenshot as a simple image lightbox. However, it can be easily used in a feedback form or other projects.

If you don’t know, in the latest updates, YouTube does the same thing when taking screenshots in their feedback form. Earlier, they used a traditional method.

If you’ve finished watching the video and fully comprehended the codes and logic, you should be aware that by modifying some codes, you can also create a Simple Video Recorder that records the video of the user’s permitted tab.

But if you haven’t watched the video tutorial, you can continue reading the blog and follow the given steps to take screenshots. Otherwise, go to the bottom of this blog post to download the source code files.

Steps for Taking Screenshots in JavaScript

To take a screenshot using HTML, CSS, and JavaScript, follow the given steps line by line:

  1. Create a folder. You can name this folder whatever you want and put the files listed below inside it.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

First, paste the following codes into your index.html file:

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Capture Screenshots with JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Font Awesome CDN Link for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Capture Screenshots with JavaScript</h1>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur deserunt exercitationem quidem, voluptate amet eius. Consequuntur obcaecati ab provident, a eveniet facilis optio dolore, ut nesciunt eaque quo tenetur similique atque voluptatibus nihil nobis facere! Recusandae totam voluptates alias eveniet perspiciatis molestias voluptatibus mollitia quaerat, doloremque dolor exercitationem, nulla delectus vero vel nihil commodi error temporibus ullam dolorem repellendus adipisci?</p>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem blanditiis aut laboriosam perspiciatis assumenda, obcaecati esse iste! Consequuntur quam cupiditate rerum quidem neque aperiam, totam iure fugit ipsam inventore debitis quod laudantium perspiciatis ea quibusdam corporis autem ullam voluptatem. Iure nam repellendus magni assumenda, ipsa soluta facere, accusamus, possimus ab quia atque provident hic repellat. Ipsa in possimus aperiam ut, eum doloribus accusamus, excepturi, vel earum cumque atque nulla a?</p>
    <h2>Dummy heading two</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore consectetur maxime eum tenetur laborum delectus necessitatibus expedita dolores perferendis saepe praesentium nostrum voluptatibus porro exercitationem ipsa maiores, veniam deleniti qui dolorum, non commodi nihil magni, tempora dicta! Facilis ducimus nam consectetur exercitationem molestias labore aspernatur repellendus itaque aliquid, esse totam ipsum. Consequuntur culpa magnam obcaecati odit reprehenderit, voluptatem iste tempore.</p>
    
    <button id="src-btn">Capture Screenshot</button>
    <div class="src-preview">
      <div class="screenshot">
        <i id="close-btn" class="fa-solid fa-xmark"></i>
        <img src="" alt="screenshot">
      </div>
    </div>

  </body>
</html>

Second, paste the following codes into your style.css file:

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
* {
  font-family: 'Poppins', sans-serif;
}
body {
  padding: 0 30px;
}
#src-btn, .screenshot {
  position: fixed;
  left: 50%;
  transform: translate(-50%, -50%);
}
#src-btn {
  bottom: 15px;
  border: none;
  outline: none;
  color: #fff;
  cursor: pointer;
  font-size: 1rem;
  padding: 15px 25px;
  border-radius: 30px;
  background: #4a98f7;
}
.src-preview {
  position: fixed;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  pointer-events: none;
  background: rgba(0,0,0,0.65);
  transition: all 0.15s ease;
}
.src-preview.show {
  opacity: 1;
  pointer-events: auto;
}
.src-preview .screenshot {
  width: 70%;
  top: 50%;
  opacity: 0;
  pointer-events: none;
  aspect-ratio: 16 / 9;
  transition: transform 0.15s ease;
  transform: translate(-50%, -50%) scale(0.9);
}
.src-preview.show .screenshot{
  opacity: 1;
  pointer-events: auto;
  transform: translate(-50%, -50%) scale(1);
}
.screenshot #close-btn {
  position: absolute;
  right: -25px;
  color: #fff;
  cursor: pointer;
  font-size: 1.1rem;
}
.screenshot img {
  width: 100%;
}

Last, paste the following codes into your script.js file: If you’re having a problem understanding the JavaScript codes, I highly recommend you watch the above YouTube video to better understand which line does what.

const screenshotBtn = document.querySelector("#src-btn"),
screenshotPreview = document.querySelector(".src-preview"),
closeBtn = screenshotPreview.querySelector("#close-btn");

const captureScreen = async () => {
    try {
        // asking permission to use a media input to record current tab
        const stream = await navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true });
        const video = document.createElement("video");
        
        video.addEventListener("loadedmetadata", () => {
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");

            // passing video width & height as canvas width & height
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            
            video.play(); // playing the video so the drawn image won't be black or blank
            // drawing an image of the captured video stream
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
            stream.getVideoTracks()[0].stop(); // terminating first video track of the stream
            
            // passing canvas data url as screenshot preview src
            screenshotPreview.querySelector("img").src = canvas.toDataURL();
            screenshotPreview.classList.add("show");
        });
        video.srcObject = stream; // passing capture stream data as video source object
    } catch (error) { // if image couldn't capture by any reason, then alert the msg
        alert("Failed to capture screenshot!");
    }
}

closeBtn.addEventListener("click", () => screenshotPreview.classList.toggle("show"));
screenshotBtn.addEventListener("click", captureScreen);

That’s all; now you’re ready to Take Screenshots in HTML CSS, and JavaScript. If your code doesn’t work or you’ve faced any problems, you can download the source code files for this project from the given download button. It’s free, and a zip file will be downloaded that contains the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/how-to-take-screenshot-vanilla-javascript/feed/ 1
Resize and Compress Images in HTML CSS & JavaScript https://www.codingnepalweb.com/resize-and-compress-images-javascript/ https://www.codingnepalweb.com/resize-and-compress-images-javascript/#comments Tue, 25 Oct 2022 10:38:23 +0000 https://www.codingnepalweb.com/?p=3035 Resize and Compress Images in HTML CSS & JavaScript

Did you know that you can resize image dimensions (width & height) and compress their size by reducing the quality on the front end using vanilla JavaScript? If your answer is no then this blog is written for you.

Today, in this blog, you’ll learn How to Resize and Compress Images in HTML CSS & JavaScript from scratch. I believe the codes and logic behind resizing images will not be complicated to understand if you already have basic knowledge of JavaScript.

In my Image Resizer & Compressor tool, users can upload an image and resize its width & height or reduce its size. If they checked the “Lock aspect ratio”, the aspect ratio for an image will be calculated automatically and filled in the field as they start changing width or height.

If the “Reduce quality” is checked, the image quality will be reduced by 40%. And, last users can download their resized images by clicking on the “Download Image” button. Remember downloading images is also done with vanilla JavaScript.

If you’re excited to know what this image resizer looks like, you can click here to view a live demo of it and try to resize your image. But, if you want to see a full video tutorial of this Resize and Compress images project, you can watch the given YouTube video.

Video Tutorial of Resize and Compress Images in JavaScript

 
I hope you liked the demo of the Image Resizer and understood how I made it using HTML CSS & JavaScript. In the video, you have seen that I didn’t use any external library to resize, compress, and download an image. It’s all done with JavaScript using canvas.

If you didn’t watch the video and want to skip it, you can skip it. But remember this image resizer tool is built using JavaScript canvas and its different methods such as getContext, drawImage, toDataURL, etc. which might be difficult for you to understand if you just copy-paste the codes.

So, I suggest you watch the video and try to understand the codes, methods, and logic of it properly. If you do so, it’ll help you to clear your confusion while recreating this image resizer by yourself or using the codes of it in your other projects. If you want more canvas-based JavaScript projects then you can see my Image Editor, Take Screenshots, Drawing App, etc.

To get source codes or files of this Image Resize and Compress project, you can easily get them from the bottom of this blog post.

You may like this:

Resize and Compress Images in JavaScript [Source Codes]

To create an Image Resizer and Compressor using HTML CSS & JavaScript, follow the given steps line by line:

  1. Create a folder. You can put any name of this folder and create the below-mentioned files inside this folder.
  2. Create an index.html file. The file name must be index and its extension .html
  3. Create a style.css file. The file name must be style and its extension .css
  4. Create a script.js file. The file name must be script and its extension .js

First, paste the following codes into your index.html file.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Image Resizer JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="wrapper">
      <div class="upload-box">
        <input type="file" accept="image/*" hidden>
        <img src="https://www.codingnepalweb.com/demos/resize-and-compress-image-javascript/upload-icon.svg" alt="">
        <p>Browse File to Upload</p>
      </div>
      <div class="content">
        <div class="row sizes">
          <div class="column width">
            <label>Width</label>
            <input type="number">
          </div>
          <div class="column height">
            <label>Height</label>
            <input type="number">
          </div>
        </div>
        <div class="row checkboxes">
          <div class="column ratio">
            <input type="checkbox" id="ratio" checked>
            <label for="ratio">Lock aspect ratio</label>
          </div>
          <div class="column quality">
            <input type="checkbox" id="quality">
            <label for="quality">Reduce quality</label>
          </div>
        </div>
        <button class="download-btn">Download Image</button>
      </div>
    </div>

  </body>
</html>

Second, paste the following codes into your style.css file.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #927DFC;
}
.wrapper{
  width: 450px;
  height: 288px;
  padding: 30px;
  background: #fff;
  border-radius: 9px;
  transition: height 0.2s ease;
}
.wrapper.active{
  height: 537px;
}
.wrapper .upload-box{
  height: 225px;
  display: flex;
  cursor: pointer;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border-radius: 5px;
  border: 2px dashed #afafaf;
}
.wrapper.active .upload-box{
  border: none;
}
.upload-box p{
  font-size: 1.06rem;
  margin-top: 20px;
}
.wrapper.active .upload-box p{
  display: none;
}
.wrapper.active .upload-box img{
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 5px;
}
.wrapper .content{
  opacity: 0;
  margin-top: 28px;
  pointer-events: none;
}
.wrapper.active .content{
  opacity: 1;
  pointer-events: auto;
  transition: opacity 0.5s 0.05s ease;
}
.content .row{
  display: flex;
  justify-content: space-between;
}
.content .row .column{
  width: calc(100% / 2 - 15px);
}
.row .column label{
  font-size: 1.06rem;
}
.sizes .column input{
  width: 100%;
  height: 49px;
  outline: none;
  margin-top: 7px;
  padding: 0 15px;
  font-size: 1.06rem;
  border-radius: 4px;
  border: 1px solid #aaa;
}
.sizes .column input:focus{
  padding: 0 14px;
  border: 2px solid #927DFC;
}
.content .checkboxes{
  margin-top: 20px;
}
.checkboxes .column{
  display: flex;
  align-items: center;
}
.checkboxes .column input{
  width: 17px;
  height: 17px;
  margin-right: 9px;
  accent-color: #927DFC;
}
.content .download-btn{
  width: 100%;
  color: #fff;
  outline: none;
  border: none;
  cursor: pointer;
  font-size: 1.06rem;
  border-radius: 5px;
  padding: 15px 0;
  margin: 30px 0 10px;
  background: #927DFC;
  text-transform: uppercase;
}

Last, paste the following codes into your script.js file.

const uploadBox = document.querySelector(".upload-box"),
previewImg = uploadBox.querySelector("img"),
fileInput = uploadBox.querySelector("input"),
widthInput = document.querySelector(".width input"),
heightInput = document.querySelector(".height input"),
ratioInput = document.querySelector(".ratio input"),
qualityInput = document.querySelector(".quality input"),
downloadBtn = document.querySelector(".download-btn");

let ogImageRatio;

const loadFile = (e) => {
    const file = e.target.files[0]; // getting first user selected file
    if(!file) return; // return if user hasn't selected any file
    previewImg.src = URL.createObjectURL(file); // passing selected file url to preview img src
    previewImg.addEventListener("load", () => { // once img loaded
        widthInput.value = previewImg.naturalWidth;
        heightInput.value = previewImg.naturalHeight;
        ogImageRatio = previewImg.naturalWidth / previewImg.naturalHeight;
        document.querySelector(".wrapper").classList.add("active");
    });
}

widthInput.addEventListener("keyup", () => {
    // getting height according to the ratio checkbox status
    const height = ratioInput.checked ? widthInput.value / ogImageRatio : heightInput.value;
    heightInput.value = Math.floor(height);
});

heightInput.addEventListener("keyup", () => {
    // getting width according to the ratio checkbox status
    const width = ratioInput.checked ? heightInput.value * ogImageRatio : widthInput.value;
    widthInput.value = Math.floor(width);
});

const resizeAndDownload = () => {
    const canvas = document.createElement("canvas");
    const a = document.createElement("a");
    const ctx = canvas.getContext("2d");

    // if quality checkbox is checked, pass 0.5 to imgQuality else pass 1.0
    // 1.0 is 100% quality where 0.5 is 50% of total. you can pass from 0.1 - 1.0
    const imgQuality = qualityInput.checked ? 0.5 : 1.0;

    // setting canvas height & width according to the input values
    canvas.width = widthInput.value;
    canvas.height = heightInput.value;

    // drawing user selected image onto the canvas
    ctx.drawImage(previewImg, 0, 0, canvas.width, canvas.height);
    
    // passing canvas data url as href value of <a> element
    a.href = canvas.toDataURL("image/jpeg", imgQuality);
    a.download = new Date().getTime(); // passing current time as download value
    a.click(); // clicking <a> element so the file download
}

downloadBtn.addEventListener("click", resizeAndDownload);
fileInput.addEventListener("change", loadFile);
uploadBox.addEventListener("click", () => fileInput.click());

That’s all, now you’ve successfully created a project on Resize and Compress Images in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It’s free and a zip file will be downloaded that contains the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/resize-and-compress-images-javascript/feed/ 4
How to Take Screenshot Easily using JavaScript https://www.codingnepalweb.com/how-to-take-screenshot-using-javascript/ https://www.codingnepalweb.com/how-to-take-screenshot-using-javascript/#comments Wed, 19 Oct 2022 11:19:20 +0000 https://www.codingnepalweb.com/?p=2988 How to Capture or Take Screenshots using JavaScript

If you’re looking for a way to take screenshot of a web page or element using JavaScript, then this blog is for you. In this blog, you’ll learn how to take screenshots and download them easily in JavaScript using the html2canvas library.

As you know, screenshots can be a valuable and vital part of web applications. Screenshots are used for multiple purposes in the application. Companies like Google use them in their feedback form while getting feedback or report from users.

Let’s talk about how to use html2canvas library to take screenshots and download the screenshots directly on the user’s device. Remember, html2canvas will be used to capture screenshots only. To download screenshots, there will use JavaScript canvas.

To take a screenshot and download it using html2canvas & JavaScript, follow the given steps line by line.

Create an index.html file and paste the given codes. If you look carefully at the code, I’ve imported the html2canvas library before the closing of </head>. There are two buttons too, which are used to take screenshots and download the screenshot.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Take Screenshot using JavaScript</title>
    <!-- Imported html2canvas library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
    <!-- Dummpy data to take screenshot -->
    <h1>Take Screenshot & Download it</h1>
    <ul>
        <li>This is a dummy list 1</li>
        <li>This is a dummy list 2</li>
        <li>This is a dummy list 3</li>
        <li>This is a dummy list 4</li>
    </ul>
    <a href="#">Dummy Link</a>
    <br>
    <p>Click the specific button to take 
        <strong>screenshot</strong> or 
        <strong>download the screenshot</strong> 
        of this page.
    </p>
    <button id="take-src-only">Take Screenshot</button>
    <button>Take Screenshot & Download</button>
    <br><br>

    <!-- Paste the script codes here -->
</body>
</html>

Once you do the above step. Paste the given codes before the closing of </body>.

<script>
  const srcElement = document.querySelector("body"),
  btns = document.querySelectorAll("button");

  btns.forEach(btn => { // looping through each btn
    // adding click event to each btn
    btn.addEventListener("click", () => {
      // creating canvas of element using html2canvas
      html2canvas(srcElement).then(canvas => {
        // adding canvas/screenshot to the body
        if(btn.id === "take-src-only") {
          return document.body.appendChild(canvas);
        }

        // downloading canvas/screenshot
        const a = document.createElement("a");
        a.href = canvas.toDataURL();
        a.download = "screenshot.jpg";
        a.click();
      });
    });
  });
</script>

That’s all, now you are ready to take a screenshot of the web page and download it. In the codes, I’ve passed the body as a screenshot element, but you can pass any element and capture a screenshot of it according to your requirement.

Conclusion

html2canvas doesn’t actually take a screenshot of the web page. It builds a representation of the page based on the properties it reads from the DOM and returns the canvas as an image. So, the image it returns may not be 100% accurate as compared to the original page. Read more about the html2canvas library.

If you don’t know, you can also capture screenshots with pure JavaScript. For more, read this blog: How to Take Screenshots in Vanilla JavaScript.

]]>
https://www.codingnepalweb.com/how-to-take-screenshot-using-javascript/feed/ 2
Build A Drawing App in HTML CSS & JavaScript https://www.codingnepalweb.com/build-drawing-app-html-canvas-javascript/ https://www.codingnepalweb.com/build-drawing-app-html-canvas-javascript/#comments Tue, 13 Sep 2022 17:08:54 +0000 https://www.codingnepalweb.com/?p=2869 Build A Drawing or Paint App in HTML CSS & JavaScript Drawing App in JavaScript

If you’ve done some beginner-level JavaScript projects and looking for an intermediate project, you can build this Drawing App that is based on HTML 5 canvas. But if you’re an absolute beginner, before building this app, I’d suggest you create some beginner-level projects from the 10 Best Beginners JavaScript Projects List.

Today in this blog, you’ll learn how to Build A Drawing or Paint App in HTML CSS & JavaScript. But before starting this project, if you haven’t seen my previous blog on Basic Image Editor in JavaScript. You can go and watch this project because many viewers have liked it and I believe you’ll like it too. Let’s back to this topic.

In this drawing app, users can draw different shapes like rectangles, circles, and triangles in their preferred colors. They can also erase or download their drawing as an image. All these functionalities are done with HTML 5 canvas & vanilla JavaScript, no external framework or library is used.

If you are excited to know what this drawing app looks like, you can click here to view a live demo of it and if you want to see a full video tutorial of this Drawing App in JavaScript, you can watch the given YouTube video.

Video Tutorial of Drawing or Paint App JavaScript

 
I hope you’ve watched the video till the end and understood the codes and logic behind building this drawing app. If you don’t want to watch the video, you can skip it but remember this drawing app is built using the canvas and its different methods which might be difficult for you to understand when you copy-paste the codes.

So, I strongly recommend you to watch the video because in the video I’ve explained each JavaScript line with written comments and also shown which code does what. If you understand the codes properly, it will help you to clear your confusion while rebuilding this drawing app by yourself or implementing the codes on your other projects.

But, if you’ve liked this drawing app and want to get source codes or files, you can easily copy-paste or download the codes from the bottom of this page. It’s free of cost.

You may like this:

Drawing or Paint App JavaScript [Source Codes]

To build a Drawing App using HTML CSS & JavaScript, follow the given steps line by line:

  1. Create a folder. You can put any name of this folder and create the below-mentioned files inside this folder.
  2. Create a index.html file. File name must be index and its extension .html
  3. Create a style.css file. File name must be style and its extension .css
  4. Create a script.js file. File name must be script and its extension .js
  5. Download the icons folder from the Google Drive and put it inside the project folder. This folder contains SVG images that are used as icons on the drawing app.

Once you create these files, paste the given codes into the specified files. If you don’t want to do these then scroll down and download the source codes of this Drawing App by clicking on the given download button.

First, paste the following codes into your index.html file

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Drawing App JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="script.js" defer></script>
  </head>
  <body>
    <div class="container">
      <section class="tools-board">
        <div class="row">
          <label class="title">Shapes</label>
          <ul class="options">
            <li class="option tool" id="rectangle">
              <img src="icons/rectangle.svg" alt="">
              <span>Rectangle</span>
            </li>
            <li class="option tool" id="circle">
              <img src="icons/circle.svg" alt="">
              <span>Circle</span>
            </li>
            <li class="option tool" id="triangle">
              <img src="icons/triangle.svg" alt="">
              <span>Triangle</span>
            </li>
            <li class="option">
              <input type="checkbox" id="fill-color">
              <label for="fill-color">Fill color</label>
            </li>
          </ul>
        </div>
        <div class="row">
          <label class="title">Options</label>
          <ul class="options">
            <li class="option active tool" id="brush">
              <img src="icons/brush.svg" alt="">
              <span>Brush</span>
            </li>
            <li class="option tool" id="eraser">
              <img src="icons/eraser.svg" alt="">
              <span>Eraser</span>
            </li>
            <li class="option">
              <input type="range" id="size-slider" min="1" max="30" value="5">
            </li>
          </ul>
        </div>
        <div class="row colors">
          <label class="title">Colors</label>
          <ul class="options">
            <li class="option"></li>
            <li class="option selected"></li>
            <li class="option"></li>
            <li class="option"></li>
            <li class="option">
              <input type="color" id="color-picker" value="#4A98F7">
            </li>
          </ul>
        </div>
        <div class="row buttons">
          <button class="clear-canvas">Clear Canvas</button>
          <button class="save-img">Save As Image</button>
        </div>
      </section>
      <section class="drawing-board">
        <canvas></canvas>
      </section>
    </div>
    
  </body>
</html>

Second, paste the following codes into your style.css file

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #4A98F7;
}
.container{
  display: flex;
  width: 100%;
  gap: 10px;
  padding: 10px;
  max-width: 1050px;
}
section{
  background: #fff;
  border-radius: 7px;
}
.tools-board{
  width: 210px;
  padding: 15px 22px 0;
}
.tools-board .row{
  margin-bottom: 20px;
}
.row .options{
  list-style: none;
  margin: 10px 0 0 5px;
}
.row .options .option{
  display: flex;
  cursor: pointer;
  align-items: center;
  margin-bottom: 10px;
}
.option:is(:hover, .active) img{
  filter: invert(17%) sepia(90%) saturate(3000%) hue-rotate(900deg) brightness(100%) contrast(100%);
}
.option :where(span, label){
  color: #5A6168;
  cursor: pointer;
  padding-left: 10px;
}
.option:is(:hover, .active) :where(span, label){
  color: #4A98F7;
}
.option #fill-color{
  cursor: pointer;
  height: 14px;
  width: 14px;
}
#fill-color:checked ~ label{
  color: #4A98F7;
}
.option #size-slider{
  width: 100%;
  height: 5px;
  margin-top: 10px;
}
.colors .options{
  display: flex;
  justify-content: space-between;
}
.colors .option{
  height: 20px;
  width: 20px;
  border-radius: 50%;
  margin-top: 3px;
  position: relative;
}
.colors .option:nth-child(1){
  background-color: #fff;
  border: 1px solid #bfbfbf;
}
.colors .option:nth-child(2){
  background-color: #000;
}
.colors .option:nth-child(3){
  background-color: #E02020;
}
.colors .option:nth-child(4){
  background-color: #6DD400;
}
.colors .option:nth-child(5){
  background-color: #4A98F7;
}
.colors .option.selected::before{
  position: absolute;
  content: "";
  top: 50%;
  left: 50%;
  height: 12px;
  width: 12px;
  background: inherit;
  border-radius: inherit;
  border: 2px solid #fff;
  transform: translate(-50%, -50%);
}
.colors .option:first-child.selected::before{
  border-color: #ccc;
}
.option #color-picker{
  opacity: 0;
  cursor: pointer;
}
.buttons button{
  width: 100%;
  color: #fff;
  border: none;
  outline: none;
  padding: 11px 0;
  font-size: 0.9rem;
  margin-bottom: 13px;
  background: none;
  border-radius: 4px;
  cursor: pointer;
}
.buttons .clear-canvas{
  color: #6C757D;
  border: 1px solid #6C757D;
  transition: all 0.3s ease;
}
.clear-canvas:hover{
  color: #fff;
  background: #6C757D;
}
.buttons .save-img{
  background: #4A98F7;
  border: 1px solid #4A98F7;
}
.drawing-board{
  flex: 1;
  overflow: hidden;
}
.drawing-board canvas{
  width: 100%;
  height: 100%;
}

Last, paste the following codes into your script.js file

const canvas = document.querySelector("canvas"),
toolBtns = document.querySelectorAll(".tool"),
fillColor = document.querySelector("#fill-color"),
sizeSlider = document.querySelector("#size-slider"),
colorBtns = document.querySelectorAll(".colors .option"),
colorPicker = document.querySelector("#color-picker"),
clearCanvas = document.querySelector(".clear-canvas"),
saveImg = document.querySelector(".save-img"),
ctx = canvas.getContext("2d");

// global variables with default value
let prevMouseX, prevMouseY, snapshot,
isDrawing = false,
selectedTool = "brush",
brushWidth = 5,
selectedColor = "#000";

const setCanvasBackground = () => {
    // setting whole canvas background to white, so the downloaded img background will be white
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = selectedColor; // setting fillstyle back to the selectedColor, it'll be the brush color
}

window.addEventListener("load", () => {
    // setting canvas width/height.. offsetwidth/height returns viewable width/height of an element
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
    setCanvasBackground();
});

const drawRect = (e) => {
    // if fillColor isn't checked draw a rect with border else draw rect with background
    if(!fillColor.checked) {
        // creating circle according to the mouse pointer
        return ctx.strokeRect(e.offsetX, e.offsetY, prevMouseX - e.offsetX, prevMouseY - e.offsetY);
    }
    ctx.fillRect(e.offsetX, e.offsetY, prevMouseX - e.offsetX, prevMouseY - e.offsetY);
}

const drawCircle = (e) => {
    ctx.beginPath(); // creating new path to draw circle
    // getting radius for circle according to the mouse pointer
    let radius = Math.sqrt(Math.pow((prevMouseX - e.offsetX), 2) + Math.pow((prevMouseY - e.offsetY), 2));
    ctx.arc(prevMouseX, prevMouseY, radius, 0, 2 * Math.PI); // creating circle according to the mouse pointer
    fillColor.checked ? ctx.fill() : ctx.stroke(); // if fillColor is checked fill circle else draw border circle
}

const drawTriangle = (e) => {
    ctx.beginPath(); // creating new path to draw circle
    ctx.moveTo(prevMouseX, prevMouseY); // moving triangle to the mouse pointer
    ctx.lineTo(e.offsetX, e.offsetY); // creating first line according to the mouse pointer
    ctx.lineTo(prevMouseX * 2 - e.offsetX, e.offsetY); // creating bottom line of triangle
    ctx.closePath(); // closing path of a triangle so the third line draw automatically
    fillColor.checked ? ctx.fill() : ctx.stroke(); // if fillColor is checked fill triangle else draw border
}

const startDraw = (e) => {
    isDrawing = true;
    prevMouseX = e.offsetX; // passing current mouseX position as prevMouseX value
    prevMouseY = e.offsetY; // passing current mouseY position as prevMouseY value
    ctx.beginPath(); // creating new path to draw
    ctx.lineWidth = brushWidth; // passing brushSize as line width
    ctx.strokeStyle = selectedColor; // passing selectedColor as stroke style
    ctx.fillStyle = selectedColor; // passing selectedColor as fill style
    // copying canvas data & passing as snapshot value.. this avoids dragging the image
    snapshot = ctx.getImageData(0, 0, canvas.width, canvas.height);
}

const drawing = (e) => {
    if(!isDrawing) return; // if isDrawing is false return from here
    ctx.putImageData(snapshot, 0, 0); // adding copied canvas data on to this canvas

    if(selectedTool === "brush" || selectedTool === "eraser") {
        // if selected tool is eraser then set strokeStyle to white 
        // to paint white color on to the existing canvas content else set the stroke color to selected color
        ctx.strokeStyle = selectedTool === "eraser" ? "#fff" : selectedColor;
        ctx.lineTo(e.offsetX, e.offsetY); // creating line according to the mouse pointer
        ctx.stroke(); // drawing/filling line with color
    } else if(selectedTool === "rectangle"){
        drawRect(e);
    } else if(selectedTool === "circle"){
        drawCircle(e);
    } else {
        drawTriangle(e);
    }
}

toolBtns.forEach(btn => {
    btn.addEventListener("click", () => { // adding click event to all tool option
        // removing active class from the previous option and adding on current clicked option
        document.querySelector(".options .active").classList.remove("active");
        btn.classList.add("active");
        selectedTool = btn.id;
    });
});

sizeSlider.addEventListener("change", () => brushWidth = sizeSlider.value); // passing slider value as brushSize

colorBtns.forEach(btn => {
    btn.addEventListener("click", () => { // adding click event to all color button
        // removing selected class from the previous option and adding on current clicked option
        document.querySelector(".options .selected").classList.remove("selected");
        btn.classList.add("selected");
        // passing selected btn background color as selectedColor value
        selectedColor = window.getComputedStyle(btn).getPropertyValue("background-color");
    });
});

colorPicker.addEventListener("change", () => {
    // passing picked color value from color picker to last color btn background
    colorPicker.parentElement.style.background = colorPicker.value;
    colorPicker.parentElement.click();
});

clearCanvas.addEventListener("click", () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // clearing whole canvas
    setCanvasBackground();
});

saveImg.addEventListener("click", () => {
    const link = document.createElement("a"); // creating <a> element
    link.download = `${Date.now()}.jpg`; // passing current date as link download value
    link.href = canvas.toDataURL(); // passing canvasData as link href value
    link.click(); // clicking link to download image
});

canvas.addEventListener("mousedown", startDraw);
canvas.addEventListener("mousemove", drawing);
canvas.addEventListener("mouseup", () => isDrawing = false);

That’s all, now you’ve successfully built a Drawing or Paint App in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It is free and a zip file will be downloaded that contains the project folder with source code files.

 

]]>
https://www.codingnepalweb.com/build-drawing-app-html-canvas-javascript/feed/ 3
Build An Image Editor in HTML CSS & JavaScript https://www.codingnepalweb.com/build-image-editor-html-javascript/ https://www.codingnepalweb.com/build-image-editor-html-javascript/#comments Fri, 15 Jul 2022 07:41:57 +0000 https://www.codingnepalweb.com/?p=2480 Build An Image Editor in HTML CSS & JavaScript

Hey friends, today in this blog, you’ll learn to create a new project named Build An Basic Image Editor in HTML CSS & JavaScript. Previously, I shared a blog on how to Build A Word Guessing Game in JavaScript that is similar to hangman.

In this project (Image Editor in JavaScript), as you’ve seen in the preview image, users can apply different filters to their image like grayscale, inversion, saturation, and adjust the image brightness. Additionally, users can also rotate or flip the images and save their edited images.

This project is made with vanilla JavaScript. If you’re excited to view a demo of this image editor or want to know what this editor looks like. You can watch the given YouTube video or click here to view a live demo of this basic image editor.

Video Tutorial of Basic Image Editor in JavaScript

 
In the above video, you’ve seen the demo of this Image Editor and how I built it with HTML CSS & Vanilla JavaScript. If you’re too beginner in JavaScript and didn’t build projects before, then this image editor code could be difficult to understand.

So, I want to suggest you build some JavaScript projects before continuing to create this image editor. But, if you’re familiar with JavaScript, the codes and logic of this project shouldn’t be difficult to understand for you.

Canvas part of the codes could be difficult to understand for you and canvas is used only to save the edited image. So, please watch the above video multiple times to understand the codes because I tried my best to explain the main JavaScript lines with written comments.

If you liked this image editor and want to get source codes and files, you can easily get them from the bottom of this page.

You might like this:

Basic Image Editor in JavaScript [Source Codes]

To build an Image Editor using HTML CSS & JavaScript, you need to create three files: HTML, CSS & JavaScript file. Once you create these files, just paste the given codes into your file. If you don’t know how to create these files, where to paste the codes, or don’t want to do these, you can simply download the source code files of this Image Editor by clicking on the given download button that is at the bottom of this page.

First, create an HTML file with the name index.html and paste the given codes into your HTML file. Remember, you’ve to create a file with a .html extension.

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/codingnepal -->
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Image Editor in JavaScript | CodingNepal</title>
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"/>
  </head>
  <body>
    <div class="container disable">
        <h2>Easy Image Editor</h2>
        <div class="wrapper">
            <div class="editor-panel">
                <div class="filter">
                    <label class="title">Filters</label>
                    <div class="options">
                        <button id="brightness" class="active">Brightness</button>
                        <button id="saturation">Saturation</button>
                        <button id="inversion">Inversion</button>
                        <button id="grayscale">Grayscale</button>
                    </div>
                    <div class="slider">
                        <div class="filter-info">
                            <p class="name">Brighteness</p>
                            <p class="value">100%</p>
                        </div>
                        <input type="range" value="100" min="0" max="200">
                    </div>
                </div>
                <div class="rotate">
                    <label class="title">Rotate & Flip</label>
                    <div class="options">
                        <button id="left"><i class="fa-solid fa-rotate-left"></i></button>
                        <button id="right"><i class="fa-solid fa-rotate-right"></i></button>
                        <button id="horizontal"><i class='bx bx-reflect-vertical'></i></button>
                        <button id="vertical"><i class='bx bx-reflect-horizontal' ></i></button>
                    </div>
                </div>
            </div>
            <div class="preview-img">
                <img src="image-placeholder.svg" alt="preview-img">
            </div>
        </div>
        <div class="controls">
            <button class="reset-filter">Reset Filters</button>
            <div class="row">
                <input type="file" class="file-input" accept="image/*" hidden>
                <button class="choose-img">Choose Image</button>
                <button class="save-img">Save Image</button>
            </div>
        </div>
    </div>

    <script src="script.js"></script>
    
  </body>
</html>

Second, create a CSS file with the name style.css and paste the given codes into your CSS file. Remember, you’ve to create a file with a .css extension.

/* Import Google font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body{
  display: flex;
  padding: 10px;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #E3F2FD;
}
.container{
  width: 850px;
  padding: 30px 35px 35px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.container.disable .editor-panel,
.container.disable .controls .reset-filter,
.container.disable .controls .save-img{
  opacity: 0.5;
  pointer-events: none;
}
.container h2{
  margin-top: -8px;
  font-size: 22px;
  font-weight: 500;
}
.container .wrapper{
  display: flex;
  margin: 20px 0;
  min-height: 335px;
}
.wrapper .editor-panel{
  padding: 15px 20px;
  width: 280px;
  border-radius: 5px;
  border: 1px solid #ccc;
}
.editor-panel .title{
  display: block;
  font-size: 16px;
  margin-bottom: 12px;
}
.editor-panel .options, .controls{
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.editor-panel button{
  outline: none;
  height: 40px;
  font-size: 14px;
  color: #6C757D;
  background: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
  border: 1px solid #aaa;
}
.editor-panel .filter button{
  width: calc(100% / 2 - 4px);
}
.editor-panel button:hover{
  background: #f5f5f5;
}
.filter button.active{
  color: #fff;
  border-color: #5372F0;
  background: #5372F0;
}
.filter .slider{
  margin-top: 12px;
}
.filter .slider .filter-info{
  display: flex;
  color: #464646;
  font-size: 14px;
  justify-content: space-between;
}
.filter .slider input{
  width: 100%;
  height: 5px;
  accent-color: #5372F0;
}
.editor-panel .rotate{
  margin-top: 17px;
}
.editor-panel .rotate button{
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(100% / 4 - 3px);
}
.rotate .options button:nth-child(3),
.rotate .options button:nth-child(4){
  font-size: 18px;
}
.rotate .options button:active{
  color: #fff;
  background: #5372F0;
  border-color: #5372F0;
}
.wrapper .preview-img{
  flex-grow: 1;
  display: flex;
  overflow: hidden;
  margin-left: 20px;
  border-radius: 5px;
  align-items: center;
  justify-content: center;
}
.preview-img img{
  max-width: 490px;
  max-height: 335px;
  width: 100%;
  height: 100%;
  object-fit: contain;
}
.controls button{
  padding: 11px 20px;
  font-size: 14px;
  border-radius: 3px;
  outline: none;
  color: #fff;
  cursor: pointer;
  background: none;
  transition: all 0.3s ease;
  text-transform: uppercase;
}
.controls .reset-filter{
  color: #6C757D;
  border: 1px solid #6C757D;
}
.controls .reset-filter:hover{
  color: #fff;
  background: #6C757D;
}
.controls .choose-img{
  background: #6C757D;
  border: 1px solid #6C757D;
}
.controls .save-img{
  margin-left: 5px;
  background: #5372F0;
  border: 1px solid #5372F0;
}

@media screen and (max-width: 760px) {
  .container{
    padding: 25px;
  }
  .container .wrapper{
    flex-wrap: wrap-reverse;
  }
  .wrapper .editor-panel{
    width: 100%;
  }
  .wrapper .preview-img{
    width: 100%;
    margin: 0 0 15px;
  }
}

@media screen and (max-width: 500px) {
  .controls button{
    width: 100%;
    margin-bottom: 10px;
  }
  .controls .row{
    width: 100%;
  }
  .controls .row .save-img{
    margin-left: 0px;
  }
}

Last, create a JavaScript file with the name script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with a .js extension.

const fileInput = document.querySelector(".file-input"),
filterOptions = document.querySelectorAll(".filter button"),
filterName = document.querySelector(".filter-info .name"),
filterValue = document.querySelector(".filter-info .value"),
filterSlider = document.querySelector(".slider input"),
rotateOptions = document.querySelectorAll(".rotate button"),
previewImg = document.querySelector(".preview-img img"),
resetFilterBtn = document.querySelector(".reset-filter"),
chooseImgBtn = document.querySelector(".choose-img"),
saveImgBtn = document.querySelector(".save-img");

let brightness = "100", saturation = "100", inversion = "0", grayscale = "0";
let rotate = 0, flipHorizontal = 1, flipVertical = 1;

const loadImage = () => {
    let file = fileInput.files[0];
    if(!file) return;
    previewImg.src = URL.createObjectURL(file);
    previewImg.addEventListener("load", () => {
        resetFilterBtn.click();
        document.querySelector(".container").classList.remove("disable");
    });
}

const applyFilter = () => {
    previewImg.style.transform = `rotate(${rotate}deg) scale(${flipHorizontal}, ${flipVertical})`;
    previewImg.style.filter = `brightness(${brightness}%) saturate(${saturation}%) invert(${inversion}%) grayscale(${grayscale}%)`;
}

filterOptions.forEach(option => {
    option.addEventListener("click", () => {
        document.querySelector(".active").classList.remove("active");
        option.classList.add("active");
        filterName.innerText = option.innerText;

        if(option.id === "brightness") {
            filterSlider.max = "200";
            filterSlider.value = brightness;
            filterValue.innerText = `${brightness}%`;
        } else if(option.id === "saturation") {
            filterSlider.max = "200";
            filterSlider.value = saturation;
            filterValue.innerText = `${saturation}%`
        } else if(option.id === "inversion") {
            filterSlider.max = "100";
            filterSlider.value = inversion;
            filterValue.innerText = `${inversion}%`;
        } else {
            filterSlider.max = "100";
            filterSlider.value = grayscale;
            filterValue.innerText = `${grayscale}%`;
        }
    });
});

const updateFilter = () => {
    filterValue.innerText = `${filterSlider.value}%`;
    const selectedFilter = document.querySelector(".filter .active");

    if(selectedFilter.id === "brightness") {
        brightness = filterSlider.value;
    } else if(selectedFilter.id === "saturation") {
        saturation = filterSlider.value;
    } else if(selectedFilter.id === "inversion") {
        inversion = filterSlider.value;
    } else {
        grayscale = filterSlider.value;
    }
    applyFilter();
}

rotateOptions.forEach(option => {
    option.addEventListener("click", () => {
        if(option.id === "left") {
            rotate -= 90;
        } else if(option.id === "right") {
            rotate += 90;
        } else if(option.id === "horizontal") {
            flipHorizontal = flipHorizontal === 1 ? -1 : 1;
        } else {
            flipVertical = flipVertical === 1 ? -1 : 1;
        }
        applyFilter();
    });
});

const resetFilter = () => {
    brightness = "100"; saturation = "100"; inversion = "0"; grayscale = "0";
    rotate = 0; flipHorizontal = 1; flipVertical = 1;
    filterOptions[0].click();
    applyFilter();
}

const saveImage = () => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.width = previewImg.naturalWidth;
    canvas.height = previewImg.naturalHeight;
    
    ctx.filter = `brightness(${brightness}%) saturate(${saturation}%) invert(${inversion}%) grayscale(${grayscale}%)`;
    ctx.translate(canvas.width / 2, canvas.height / 2);
    if(rotate !== 0) {
        ctx.rotate(rotate * Math.PI / 180);
    }
    ctx.scale(flipHorizontal, flipVertical);
    ctx.drawImage(previewImg, -canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
    
    const link = document.createElement("a");
    link.download = "image.jpg";
    link.href = canvas.toDataURL();
    link.click();
}

filterSlider.addEventListener("input", updateFilter);
resetFilterBtn.addEventListener("click", resetFilter);
saveImgBtn.addEventListener("click", saveImage);
fileInput.addEventListener("change", loadImage);
chooseImgBtn.addEventListener("click", () => fileInput.click());

That’s all, now you’ve successfully built a Basic Image Editor in HTML CSS & JavaScript. If your code doesn’t work or you’ve faced any problems, please download the source code files from the given download button. It is free and a zip file will be downloaded that contains project folder with source code files.

 

]]>
https://www.codingnepalweb.com/build-image-editor-html-javascript/feed/ 11