The image is being loaded onto the canvas and is being resized

Currently, I am facing an issue with loading images into a canvas element as the image seems to be scaled in some way.

To provide some context, I have multiple canvases on my webpage and I want to load images into them. Since the dimensions of the canvas depend on the screen size, I am uncertain about how to handle this. Therefore, I create a div and canvas, use CSS to set the size accordingly, and then print an image onto the canvas. There are additional tasks related to manipulating the image based on ratio such as centering it vertically or horizontally, but these are not the main concern right now. The main problem is that the image appears "zoomed in".

For example, here is the relevant JavaScript code:

$("canvas").each(function() {
  var context = $(this)[0].getContext('2d');
  var img = new Image;

  img.src = 'http://i67.tinypic.com/n38zdv.jpg';

  $(img).load(function() {
    context.drawImage(this, 0, 0);
  });

//img will print 400 (correct, thats the width of the img)
//canvas will print based on the screen size (correct)
//img displayed in the canvas shows 300px out of 400px, it's zoomed (not correct)
  $(this).parent().append(
    'img width: '+img.width+
    ', canvas width: '+$(this).width());
});

You can view the complete example with HTML and CSS here.

I am currently testing this on Mac, and both Safari and Chrome exhibit the same zoom issue.

Your assistance with resolving this matter would be greatly appreciated. Thank you!

Answer №1

drawImage allows you to set the width and height of the image. To get the canvas width, use the following code snippet:

$("canvas").each(function() {
  var canvas = this;
  var context = canvas.getContext('2d');
  var img = new Image;
  img.src = 'http://i67.tinypic.com/n38zdv.jpg';

  $(img).load(function() {
    context.drawImage(this, 0, 0, canvas.width, canvas.height);
  });
});

View your code in action here:

https://jsfiddle.net/ucxdLsq9/

For more information on the different drawImage signatures, refer to the documentation available here:

https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/drawImage

Answer №2

Make sure to set the correct width and height for the drawImage function.

context.drawImage(this, 0, 0 ,350 ,200);

See the modified demo here

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

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

Update: Explored 0 web pages (at a rate of 0 pages per minute) and obtained information from 0 elements (at a rate of

I'm a beginner in Python and Scrapy, currently working on my first project to crawl web security information from a website. However, when I try to run it using cmd, I encounter the message "Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 item ...

One or multiple web browsers set in the Browserslist of the project

I have recently started working with the Ionic framework and encountered some warnings while setting up my application. Can anyone help me with a solution? [ng] When starting the Ionic application, I received the following warnings: [ng] One or more browse ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...

How to display only the thumbnail on WordPress archive page and remove the post excerpt

I am currently in the process of revamping my category archive to resemble a grid layout by utilizing custom CSS. I have successfully eliminated the elements I desired using code like this: .archive .entry-footer { display: none; } Now, I only have t ...

Loading images dynamically in ReactJS allows for a seamless and customized user experience

I've been trying to dynamically fetch images from my images folder based on data retrieved from the database. Despite searching through numerous resources, I'm still struggling to crack this issue. Check out my code snippet below: import sword fr ...

React Native error - "Invalid element type: expected a string or class/function, but received undefined" - encountering issue with importing a custom library?

Alright, I'm looking to make some modifications to this library, so I am attempting to import the non-transpiled version by downloading the repository and importing it from here: https://github.com/nicotroia/react-native-floating-action-menu#readme A ...

Issues with Mouse Hover/Image Replacement

In this particular example, I am attempting to achieve a simple functionality where an image changes when the mouse hovers over it, and reverts back to the original image when the mouse is no longer hovering. However, despite my efforts, there seems to be ...

Chrome's struggle with displaying multiple backgrounds on retina screens due to CSS complications

My goal is to create top and bottom shadows for a parent container when scrolling through the content. This effect works perfectly everywhere except on Chrome browser with retina screens, where it behaves strangely. The background becomes stuck at the top, ...

Create a visually stunning CSS3 animation within a specified container, mimicking the style shown in the

I'm currently working on creating the animation depicted in the image below: https://i.stack.imgur.com/W69EQ.jpg My goal is to develop a video slider where, upon clicking a button, the video will seamlessly shift to the right within its parent conta ...

Align button text vertically in the middle using Flexbox with Bootstrap 4

Why is the text in the button displaying at the top instead of the center when using internet explorer? button { height: 100px; } <div class="container"> <button class="w-100 f-default-f btn btn-primary d-flex justify-content-between px-3"& ...

Ensure the div element remains fixed at the top of the page

I created a script to identify when I reach the navigation bar div element and then change its CSS to have a fixed position at the top. However, I am encountering an issue where instead of staying fixed, it jumps back to the beginning of the screen and fli ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

Update all project files in Firebase authentication

A client-side project is being developed using firebase and vue. After a successful login by the user, the authService object gets updated in the Login component, but not in the router. The authService is utilized in both the Login component and AdminNavba ...

JavaScript allows users to create a single string by merging multiple strings positioned at various points

Let's say we have 3 strings: s1 = "ab", s2 = "cd", s3 = "ef". The task is to form a new string by merging s1, s2, and s3. The twist here is that the user has the freedom to choose the positions of these 3 strings. For example: s1 - position 3; s2 - ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

What is the reason that Gatsby's arrow function is unable to access a value from props that is calculated from a promise?

Could someone shed light on why the key value is showing as undefined within the arrow function: // in parent component const Parent = () => { const [key, setKey] = useState<string>(); // this contains an expensive function we on ...

Having trouble importing a module or library in VueJS?

After setting up a slider library called Hooper in VueJS 3, I imported it locally like this: <template> <hooper> <slide>1</slide> <slide>1</slide> <slide>1</slide> <slide>1</slide&g ...

`Can you guide me on the proper path for designing this website layout?`

As I embark on creating my first website, I have a specific vision in mind. I want the full display on a computer screen to show all the information and links without any need for scrolling. However, when the window is resized to smaller screens, I would l ...

What are the differences in using ng-controller versus data-ng-controller?

When working with Angularjs, how do I determine whether to use data-ng-controller or ng-controller? In terms of current best practices for good software design, when is it appropriate to use each one? The information cited suggests that data-ng-controlle ...