The putImageData function in HTML5, CSS, and JS does not automatically resize or adjust the video/image to fit within the canvas

I am facing an issue with resizing an image and it doesn't recognize the new size even when I set it:

To better explain my problem, I have created a fiddle to show what I'm trying to achieve: https://jsfiddle.net/lightblue/w7tq3yrc/7/

Despite setting the width and height of both the image and canvas, the image does not resize accordingly and maintains its original dimensions.

ctx.putImageData(imgd, 20, 20);

How can I adjust it to properly fit within the specified height and width?

If there is a recommended library that can assist with this issue, I am open to suggestions.

Answer №1

The dimensions of the image you are using are 48 by 48 pixels. To display a 20 by 20 image on the canvas, you should apply this code:

ctx.drawImage(image, 0, 0, 20, 20);

Furthermore, when fetching the image data, avoid using: ctx.getImageData(0, 0, 45, 45),. Instead, since you are working with a 20 by 20 canvas, use this format: ctx.getImageData(0, 0, 20, 20)

I hope this clarification is helpful.

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    image = document.getElementById("testImage");

// Fill screen with red, green, and blue stripes.
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 20, 20);

ctx.drawImage(image, 0, 0, 20, 20);

var imgd = ctx.getImageData(0, 0, 20, 20),
    pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
    var r = pix[i],
        g = pix[i + 1],
        b = pix[i + 2],
        a = pix[i + 3];
    if (r < 60) {
        pix[i + 2] = 20;
    }
}

ctx.putImageData(imgd, 20, 20);
<h3>Original Image</h3>

<img id="testImage" src='data:;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

What is the best way to store the checkbox value in Firestore?

I have a checkbox that allows the user to select all checkboxes. However, I am facing an issue when trying to save this data in Firestore. Every time I submit it, I receive the following error message: TypeError: s.indexOf is not a function If I check al ...

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

Tips for keeping divs in place when hovering over a changing-sized element above them

Looking for some help with my website design. Whenever I hover over the "Problem" and then move away, the div underneath it shifts up and down. The same issue occurs when interacting with the "Solution" section. Any suggestions on how to prevent this movem ...

Tips for retrieving the output from an Azure Function

Just getting started with Azure Functions and I have this code snippet: module.exports = function (context, req) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(context.req.body.videoId) ...

Plugin for jQuery menu with animated background-position and no images

Check out the example I created here. I'm not certain if this is the most optimal approach. Are there alternative solutions for this menu that do not involve images or background-position animation plugins? Apologies for any language errors - thanks, ...

Is the radio functionality and dropdown menu experiencing technical difficulties?

I'm having issues with my code, specifically in the JS function when I try to retrieve values from radio buttons and dropdown menus. Can someone help me figure out what's going wrong? CSS: #mytable { width:400px; border: 1pt solid blac ...

Highlighting the menu items when hovering over them in an ASP menu

Recently, I have been working on my menu code and here is what I currently have: <td><a href="Products.asp?isnew=true"><img height="21" border="0" src="images/productmenu/new_items<%if request.querystring("isnew")="" then%><%else%& ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Is it possible to use an SVG image as a border with a variable height in CSS

Check out this jsfiddle for my current project's nav setup. I want to center the logo in the middle of the nav with three links centered around it. However, I need the design to be responsive across various screen widths. Any advice on how to achieve ...

executing tasks on a sql database with php

Currently, I am delving into the realm of SQL and have devised a table named products. This table consists of columns such as item, price, base, and wholesale. My goal is to enable users to input a number (let's say 15) which signifies their desire t ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

Use the fetch method to send a request from an HTML file that is being served through a

In my current setup, I have this code snippet to serve an HTML file via Go server. func main() { http.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) { path := r.URL.Path if path == "/" { pa ...

Setting images on various screens with Bootstrap can be achieved by utilizing the responsive class utilities

Is it possible to display 2 images on a small screen and 4 images on a large screen using Bootstrap? How can this be achieved? <div class="row"> <div class="col-sm-6 col-md-3 col-lg-2"> <img src=""> </ ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

The router component in "react-router-dom" is not functioning properly

My goal is to explicitly utilize history in my project. While I am familiar with BrowserRouter, I prefer to use Route and make history one of its properties. Upon running the program, I encounter this page: enter image description here Below is my AppRout ...

Tips for formatting strings to be compatible with JSON.parse

I'm encountering an issue with my node.js application where I am attempting to parse a string using JSON.parse. Here is the code snippet: try{ skills = JSON.parse(user.skills); }catch(e){ console.log(e); } The string stored in user.skill ...

Using the ternary operator to insert elements from one JavaScript array into another array

In my React form, I am dealing with an array of objects that represent different fields. Depending on a boolean state, I need to dynamically change the sequence of fields displayed. While I have no trouble inserting a single object into the array, I am s ...

What is preventing the X-Powered-By Header from being disabled even after implementing helmet security measures?

After incorporating Helmet into my Express application and configuring it in app.js with the following code: app.use(helmet()); const helmet = require('helmet'); Upon restarting the app, the X-Powered-by header is still enabled despite using app ...

Decoding the `this` Mystery in VueJS

Recently, I decided to delve into the world of VueJS starting from square one. Following their official guide has been a helpful resource, but I've hit a roadblock at this section. One particular example in the guide caught my attention... var app5 = ...

Having issues with the input event not triggering when the value is modified using jQuery's val() or JavaScript

When a value of an input field is changed programmatically, the expected input and change events do not trigger. Here's an example scenario: var $input = $('#myinput'); $input.on('input', function() { // Perform this action w ...