Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) {
    var canvas = document.createElement("canvas");
    if (img.width * img.height < 921600) { // Less than 480p
        canvas.width = 1920;
        canvas.height = 1080;
    } else if (img.width * img.height > 2073600) { // Greater than 1080p
        canvas.width = img.width;
        canvas.height = img.height;
    }
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL("image/jpg");
    return dataURL.replace(/^data:image\/(jpg);base64,/, "");
}

I need to adjust the resolution of an image before uploading it. If the image is less than 480p, I want to increase its size to 480p on canvas. If the image is greater than 1080p, I want to reduce it to 1080p on canvas.

Is there a way to set minimum and maximum width and height for the canvas, or any alternative method to modify the image's resolution before uploading?

Answer №1

Below is a quick solution, but keep in mind that there may be room for code improvement:

 function encodeImageToBase64(img) {
    var canvas = document.createElement("canvas");
    let image = document.createElement("img");
    image.setAttribute("src", img);

    setTimeout(function(){
        if(image.height == 1080){
            canvas.width = 1920;
            canvas.height = 1080;
        }
        if(image.height == 480){
            canvas.width = 640;
            canvas.height = 480;
        }
    },0)

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
    var dataURL = canvas.toDataURL("image/jpg");
    return dataURL.replace(/^data:image\/(jpg);base64,/, "");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging Forms for Entering Google Maps Information

Recently, I've been working on an app that aims to generate a custom map based on user input from a form. If you'd like to test the functionality yourself, head over to this page. After filling out all required fields and hitting "Submit", the g ...

Controller receiving empty object array from FormData

I am encountering an issue with my ajax call to the controller, where I am passing FormData() containing an array of objects and other properties. The list array that I pass seems to have 0 elements in the controller. Can anyone assist me with this problem ...

Looking for an iframe that can adapt to varying content sizes and scale seamlessly with different screen dimensions?

I am new to advanced coding and currently working on my first responsive Wordpress site. I have a "Product Search" database/site that I'm trying to integrate into my website using an iFrame. I want the integration to look seamless without scroll bars ...

Implement a mandatory parameter in the URL route using ui-router

My Angular routing configuration using ui-router is quite simple: $stateProvider .state("master", { abstract: true, url: "/{tenantName}" }) .state("master.home", { url: "", }) .state("master.login ...

Preventing line breaks (endline) from PHP variable when passing to JavaScript

Check out my code snippet below: <td onclick="openFile('<?php echo htmlentities ($row['name'])?>',' <?php echo htmlentities ($row['content'])?>')"> <a href="#nf" dat ...

Mastering the art of square bracket destructuring in React through deep comprehension of the concept

import React, { useEffect, useState } from 'react' import { Text } from 'react-native' export default function Counter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => setCount((co ...

The header appears distorted on older versions of Internet Explorer, specifically IE 7 and IE

The website I am currently working on looks great in Chrome, Firefox, Opera, and Safari on both Mac and Windows. However, it is not displaying correctly in IE 7 & 8. The header should appear like this: But in Internet Explorer, it's showing up like t ...

Tips for displaying the Font Awesome icons

I have included Font Awesome icons within the <span> tags and applied the necessary styles in my CSS file. However, the icon is not being displayed correctly. I am looking for a solution to ensure the correct display of the icons. The HTML code wher ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

What is the ideal approach for setting up the react-native CLI - local module or global installation

I've been following the initial steps to start with React Native from FB's git page at https://facebook.github.io/react-native/docs/getting-started While using nxp or npm installed CLI during the process, I encountered the following error. [!] ...

MenuIcon Component is experiencing difficulty being rendered

I am attempting to construct an IconMenu within the AppBar Component. My project is being developed using create-react-app. This is how my code appears: index.js import React from 'react'; import ReactDOM from 'react-dom'; import &a ...

Is there a way to customize the checkout page using JavaScript?

I'm working on a checkout page where fields need to change based on a selected radio button. There are two options: A and B. When A is selected, I want certain fields to remain visible while others disappear, and vice versa for option B. Although I p ...

Discovering all the links present on a webpage using node.js

Currently, I am diving into node.js (webdriver) and encountering some challenges. Despite my efforts to search online for examples of the tasks I need help with, I have come up empty-handed. One example that has me stumped is how to log all links from a pa ...

I am experiencing an issue with environment variables not appearing in my Context component on Next.js. Should I adjust the Next.js configuration or set up the Context to properly utilize the variables?

Why are Environment Variables working on every component inside /pages but not in my Context component in Next.js? Do I need to do some configuration in Next.js for this? (Note: The Shopcontext.tsx file is using a class component that I obtained from a tu ...

Dimming the background of my page as the Loader makes its grand entrance

Currently, I am in the process of developing a filtering system for my content. The setup involves displaying a loader in the center of the screen whenever a filter option is clicked, followed by sorting and displaying the results using JQuery. I have a v ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Access another page by clicking on a link within an HTML document

Is it possible to include an anchor tag in demo1.html that, when clicked, will take the user to the demo2.html page and automatically select a data filter on that page? Here is the code snippet for demo1.html: <li> <div><a href="urunli ...

Implementing CSS and JS for targeted elements or functions in WordPress

I am currently managing a WordPress WooCommerce website My goal is to implement bootstrap CSS and js specifically for a function on my WooCommerce checkout page. The code I have written is as follows: if( current_user_can('administrator')) { fu ...

Error: The function react__WEBPACK_IMPORTED_MODULE_6___default.a.useState is not defined as a function

Hey there! I have been working on some ReactJS code using material-ui, but it seems like I made a mistake with the placement of function handleClickOpen() and function handleClose(). Unfortunately, now my code doesn't compile. Can you help me fix it? ...

What is the reason for the error message saying "The prefix 'h' for the element 'h:head' is not bound"?

Below is the xhtml code I have created: <html> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/> </h:head> <h:body> <view> <h:form> <br/> ...