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

Expanding the jQuery AutoComplete Plugin: A Guide to Implementing the bind keyup Event

Currently, I am utilizing a plugin that enhances the features of the jQuery AutoComplete UI Plugin: https://github.com/experteer/autocompleteTrigger/blob/master/jquery-ui.autocompleteTrigger.js Within the select method, an event and ui variable are passe ...

Attempting to align the text perfectly while also adding a subtle drop shadow effect

Trying to center text with a drop shadow without using the CSS property. I'm utilizing span and :before for cross-browser compatibility. Here is what it currently looks like: The HTML: <h3 title="Say hello to Stack Overflow"><span>Say ...

What's the best way to ensure uniform card height in Material-UI?

Is there a way to ensure consistent card height in Material-UI without setting a fixed height? I want the card heights to dynamically adjust based on content, with all cards matching the tallest one on the website. How can this be achieved while also addin ...

Total of Vue Component Subtotals

One of the challenges I'm facing in my Vue app is calculating the total of subtotals. Every component has its own subtotal that depends on user input. I need to combine these individual subtotals and display the result in an input field outside of th ...

Using JQuery, remove any duplicate items from one list box and populate another list box

I have two list boxes set up: the leftBox contains all available options, while the rightBox displays the selected options. I am already familiar with how to add and remove items from each list box using jquery. However, my current goal is to automatically ...

Export a function within a function to be used in another file in Javascript

I'm encountering an issue regarding exporting a function within a function to another function in a separate file, while working with the React framework. The code snippet provided below is not functioning as expected, despite my attempts to troubles ...

Implement a feature that adds a circle element when an image is clicked in a React application

I am attempting to create a program that allows users to add circles to an image by clicking on it. Essentially, when the user clicks at coordinates (x,y), a circle with a radius of 10 will appear at that location. I am exploring ways to implement meta-pro ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

Error: Unable to extract the 'id' property from 'this.props.Name' because it is undefined in ReactJS

Can you please assist me in resolving this issue? Error: Cannot destructure property 'id' of 'this.props.Name' as it is undefined. src/component/Detail.js file import React, { Component } from 'react'; import { Character } f ...

Issues with Vue Sortable functionality may be causing complications

Currently, I am utilizing vue-sortable and draggable. Although I am able to drag an item above and change its position, the JSON data does not refresh. Here is the existing list: <draggable v-model="this.$store.getters.getDocument.getDocumentAttributes ...

When utilizing the vue @submit directive, the FormData object may be found to be devoid

Encountering a unique edge case, I found a solution. When creating a form with Vue, I noticed that empty strings were being sent to the server. Upon investigation, it became apparent that the issue lies within the @submit directive. Interestingly, when uti ...

Updating the hyperlink of an html element using css

I am looking to update this A tag <a href="contact.html" >Contact</a> to <a href="tel:+13174562564" >Contact</a> using only CSS, if possible. Alternatively, like this <a href="tel:+13174562564" >+13174562564</a> ...

When attempting to swap out ":customimage:" with an image in a React.js HTML view, the result displayed is [object Object]

I have created a function below: WordColonsToImage(comment) { var newcomment = comment.replace(/:wave:\s*/g, <img src={wavinghand} />) return newcomment } Here is an example: WordColonsToImage("Hi! :wave:") whi ...

Having trouble with the line of code right before a $timeout in AngularJS

I am wondering about an issue in my code. vm.showSuccess = true; $timeout(function() { close(); }, 2000); vm.showSuccess = false; Interestingly, the timeout function is executing properly but the first line seems to be ignored. This piece of code is me ...

The TypeScript script does not qualify as a module

Just starting out with TypeScript and encountering a simple issue. I'm attempting to import a file in order to bring in an interface. Here's an example: Parent: import { User } from "@/Users"; export interface Gift { id: number; ...

What is the most effective method for establishing a notification system?

My PHP-based CMS includes internal messaging functionality. While currently I can receive notifications for new messages upon page refresh, I am looking to implement real-time notifications similar to those on Facebook. What would be the most efficient ap ...

Email header image alignment issue in Thunderbird

I recently created an HTML email using a template and it looks great on most platforms, but not in Thunderbird. The header image is not aligned properly above the content as shown in the screenshot. Does anyone know how to troubleshoot this issue or have a ...

Top Method for Reloading Element-Specific JavaScript When Replacing Elements

Is there a better way to re-initialize JavaScript without needing a page refresh? I'm currently struggling with appending an MDBootstrap <select> tag, which involves more than just adding a child element. Instead, I have to remove the element an ...

Empty Ajax array sent to PHP

I am encountering an issue with my ajax form where the values in an array are coming out as null in my PHP response. I suspect that there may be a mistake in my .ajax call. Can anyone provide suggestions or insights on how to resolve this issue? My code sn ...

Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...