Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / Resize Image JavaScript Using Canvas

Resize Image JavaScript Using Canvas

January 22, 2024January 21, 2024 by Asif Mughal
Resize Image JavaScript Using Canvas
Share This:
Code Snippet:Resizing Images in JavaScript Simplified
Author: Envato Tuts+
Published: January 21, 2024
Last Updated: January 22, 2024
Downloads: 1,613
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code provides a way to resize images using the HTML canvas element. It allows you to specify a new width and/or height for an image, and it will create a resized version of the image on the canvas. This functionality is helpful for adjusting image dimensions without altering the original image file.

You can use this code in web applications to dynamically resize images. It’s beneficial for creating responsive websites, optimizing image sizes for faster loading, and providing users with downloadable resized images.

How to Create Resize Image Functionality in Javascript Using Canvas

1. In the first step, load the Normalize CSS and Google Fonts by adding the following CDN links into the head tag of your webpage. (Optional)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Dosis'>

2. Create the HTML structure to resize the image dynamically. Include an <h2> element for a title, an <a> tag for image credit, a <canvas> element to display the resized image, and a button with the class “download” to allow users to download the resized image. Update the imagePath variable with the actual path of your image that you want to resize.

<h2>Resizing Images in JavaScript</h2>
<p>Image Credit: <a href="https://pixabay.com/photos/tulips-flowers-field-sky-6897351/">Pixabay</a></p>
<div><canvas id="canvas"></canvas></div>

<div><button class="download">Download Image</button></div>

<script>
  imagePath = "path/to/your-image.jpg";
</script>

3. The following CSS code ensures proper styling for your HTML elements. It defines basic styles for various elements like body, canvas, input, and buttons. You can modify the CSS code according to your project requirements.

* {
  padding: 0;
  margin: 0;
  boxz-sizing: border-box;
}

body {
  margin: 20px auto;
  font-family: 'Dosis';
  font-weight: 300;
  text-align: center;
  font-size: 1rem;
}

canvas {
  margin: 20px auto;
}

input {
  border: none;
  border-bottom: 1px  solid black;
  font-family: 'Dosis';
  margin: 1rem;
  text-align: center;
  outline: none;
  width: 200px;
}

button {
  background: yellowgreen;
  border: 2px solid black;
  color: black;
  border-radius: 5px;
  padding: 1rem 2rem;
  cursor: pointer;
  font-family: 'Dosis';
}

h2 {
  margin: 1rem 0;
}

div.wrapper {
  display: flex;
  flex-direction: column;
}

form {
  display: flex;
  justify-content: center;
}

label {
  margin: 0 1rem;
  color: gray;
}

4. Finally, use the following JavaScript code to resize images dynamically. The resizeImage function takes three parameters: imagePath (the path to your image), newWidth, and newHeight. It resizes and displays the image on the canvas element. Make sure to call this function with the desired parameters to resize your image.

//resize and draw the image on first load
resizeImage(imagePath, 360, 240);

//resize the image and draw it to the canvas
function resizeImage(imagePath, newWidth, newHeight) {
    //create an image object from the path
    const originalImage = new Image();
    originalImage.src = imagePath;
 
    //get a reference to the canvas
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
 
    //wait for the image to load
    originalImage.addEventListener('load', function() {
        
        //get the original image size and aspect ratio
        const originalWidth = originalImage.naturalWidth;
        const originalHeight = originalImage.naturalHeight;
        const aspectRatio = originalWidth/originalHeight;
 
        //if the new height wasn't specified, use the width and the original aspect ratio
        if (newHeight === undefined) {
            //calculate the new height
            newHeight = newWidth/aspectRatio;
            newHeight = Math.floor(newHeight);
            
            //update the input element with the new height
            hInput.placeholder = `Height (${newHeight})`;
            hInput.value = newHeight;
        }
      
        //set the canvas size
        canvas.width = newWidth;
        canvas.height = newHeight;
         
        //render the image
        ctx.drawImage(originalImage, 0, 0, newWidth, newHeight);
    });
}

const downloadBtn = document.querySelector("button.download");
 
//a click event handler for the download button
//download the resized image to the client computer
downloadBtn.addEventListener('click', function() {
    //create a temporary link for the download item
    let tempLink = document.createElement('a');

    //generate a new filename
    let fileName = `image-resized.jpg`;
  
    //configure the link to download the resized image
    tempLink.download = fileName;
    tempLink.href = document.getElementById('canvas').toDataURL("image/jpeg", 0.9);
  
    //trigger a click on the link to start the download
    tempLink.click();
});

That’s all! hopefully, you have successfully integrated this JavaScript code to resize image using Canvas element. If you have any questions or suggestions, feel free to comment below.

Similar Code Snippets:

  • Smooth Scroll to Top in JavaScript

    Smooth Scroll to Top in JavaScript

  • Tic Tac Toe Game 2 Player JavaScript

    Tic Tac Toe Game 2 Player JavaScript

  • JavaScript Check if Image is Portrait or Landscape

    JavaScript Check if Image is Portrait or Landscape

  • Simple Calculator Code In HTML and JavaScript

    Simple Calculator Code in HTML and JavaScript

  • JavaScript Sort Table on Header Click

    JavaScript Sort Table on Header Click

  • JavaScript Dark Mode Toggle with Local Storage

    JavaScript Dark Mode Toggle with Local Storage

  • Weight Loss Calculator using JavaScript

    Weight Loss Calculator using JavaScript

  • SVG Cubic Bezier Curve Generator in JavaScript

    SVG Cubic Bezier Curve Generator in JavaScript

  • Img Comparison Slider using Vanilla JS

    Img Comparison Slider using Vanilla JS

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript Tags HTML5 Canvas
Breakout Game with Vanilla JavaScript
Mask Image and Text Using CSS Clip Path and SVG

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,397 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,935 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,948 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,357 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,036 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,103 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,392 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,388 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,146 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,199 views

Advertisement

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

Please Rel0ad/PressF5 this page if you can't click the download/preview link

F5
X