The ctx.drawImage function is drawing only half of the image

I am attempting to upload an image and then display it on a canvas, but at the moment I can only get half of the image to render:

let picture = new Image();
picture.crossOrigin = 'Anonymous';
picture.onload = function() {
  let canvas = document.createElement('canvas'),
      ctx = canvas.getContext('2d');
  ctx.drawImage(picture, 0, 0);
  canvas.style.position = 'absolute';
  canvas.style.top = 0;
  canvas.style.left = 0;
  document.body.appendChild(canvas);
}
picture.src = 'https://s3.amazonaws.com/duhaime/blog/visualizations/word-to-viz/heightmap.jpg';

Can anyone identify what might be causing the issue in the code above? Your suggestions would be greatly appreciated!

Answer №1

Because the canvas size is smaller than image

To ensure that the entire image is visible, adjust the canvas size accordingly.

let picture = new Image();
picture.crossOrigin = 'Anonymous';
picture.onload = function() {
  let canvas = document.createElement('canvas');
  canvas.width = picture.width;
  canvas.height = picture.height;
  let context = canvas.getContext('2d');
  context.drawImage(picture, 0, 0);
  document.body.appendChild(canvas);
}
picture.src = 'https://s3.amazonaws.com/duhaime/blog/visualizations/word-to-viz/heightmap.jpg';


If needed, you can set the canvas size using CSS without changing its dimensions (the CSS will just stretch it).

//same code as above
let picture = new Image();
picture.crossOrigin = 'Anonymous';
picture.onload = function() {
  let canvas = document.createElement('canvas');
  canvas.width = picture.width;
  canvas.height = picture.height;
  let context = canvas.getContext('2d');
  context.drawImage(picture, 0, 0);
  document.body.appendChild(canvas);
}
picture.src = 'https://s3.amazonaws.com/duhaime/blog/visualizations/word-to-viz/heightmap.jpg';
canvas{width:200px; height:100px;}

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

Submitting a Form with JQuery/AJAX and PHP

As I navigate through the world of form submissions in JQuery/AJAX and PHP, I find myself facing some challenges. While following online tutorials to learn, there are a few roadblocks that have cropped up. My goal is to create a form that can process subm ...

Comparing current time with a given hour string in JavaScript

Seeking assistance with comparing the hour attribute string Time:"10:50" in JavaScript to the current system hour. For example, if the hour is 10, then run a code in a function. Any guidance on how to achieve this would be greatly appreciated. Thank you. ...

Determining the decimal power using the position of a for-loop

After selecting a number, the task is to generate circles using d3.js. Each circle will be assigned a color from an array: var color =["red", "blue", "yellow", "orange",.....] ● For instance, if the user picks 593, the first 500 circles should be ...

How to invoke a function from a different ng-app in AngularJS

I have 2 ng-app block on the same page. One is for listing items and the other one is for inserting them. I am trying to call the listing function after I finish inserting, but so far I haven't been successful in doing so. I have researched how to cal ...

Utilizing Google Maps API version 3 to display various groups of markers

I am encountering an issue while trying to plot fixed markers and a user position marker on a Google Map. I want to use different images for these markers, but something strange is happening. When the page loads, all fixed markers show up correctly initial ...

How can you resize a circle in Three.js without resizing its outline?

I'm currently using a THREE.Path to generate a Circular path and then utilizing a TubeGeometry to form a circle with transparent fill and an adjustable stroke thickness. My main query revolves around the process of scaling up the Circular path dynamic ...

What is the best way to access the element menu with element-ui?

I am looking for a way to programmatically open an element in my menu, but I haven't been able to find any information on how to do it. HTML <script src="//unpkg.com/vue/dist/vue.js"></script> <script src="//unpkg.com/<a hr ...

What is preventing array.map() from being a function?

I am facing an issue when trying to map an array from the useState hook in react. The error message that I am getting is: TypeError: documents.map is not a function Here is the code snippet that I am working with: const [docs, setDocs] = useState(docume ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

Steps for conducting a targeted element check within an array property in MongoDB

Currently, I am working on optimizing my code running on a node server. Specifically, I am focusing on improving the filtering aspect related to something known as "content" within its schema. const contentSchema = new Schema({ title: String , skills :[ { ...

Identifying the pressing of the enter key in an input field

Currently, I am developing an innovative IFrame browser that features an omnibox (identified as "address") and a "GO" button (identified as "submit"). One of the key challenges I'm facing is detecting when the user inputs information and hits the Ente ...

Create a form based on a bootstrap table row

this is my sample. I want to implement a feature where clicking on a row will display a form at the bottom of the page for user correction. I have used jquery .html() to render the lower table, but I'm unsure how to set up an input form for it. this ...

Clickable headline in Boostrap 5 accordion

I'm in the process of incorporating a clickable help feature into my Bootstrap 5 accordion, as shown in the following screenshot: https://i.sstatic.net/G8rDI.png The idea is to allow users to click on the question mark icon, which will then trigger ...

Ways to restrict the number of times elements are iterated in a `v-for`

Currently developing a compact application using Vuejs 2.0. There are around 15 elements that need to be iterated, but I would like to restrict v-for to only display 5 at a time, with additional buttons for viewing the entire list. Is it feasible to achi ...

Obtain asynchronous state in VueJS without the need for intricate v-if conditions

I am working on an application that heavily relies on Vue-Router and Vuex for state management. Within the Dashboard component, important user information is displayed. This data is fetched asynchronously from a database by Vue and then stored in Vuex. T ...

Clicking outside the box will close it

I received a code from the internet that allows me to click on text and open a box. However, I am looking to add functionality to close the box when I click outside of it. Here is the javascript code I am using: function setVisibility(id, visibility) { ...

Error with SwitchMap on ActivatedRoute.paramMap

When I try to run the ngOnInit method of my component, I encountered an error with the following line of code. this.products$ = this.route.paramMap.switchMap((params: ParamMap) => this.getProductsForType(params.get('type'))); The error mes ...

An error occurred when attempting to access the 'selectedZones' property of an undefined variable that has already been initialized and is not empty

I'm troubleshooting an issue with my component that filters build zones based on selected zones in the ngOnInit lifecycle hook. rfid.component.ts @Component(...) export class RfidComponent implements OnInit { gridApi: GridApi; partList = new Be ...

Generate a biscuit within a text field while typing, then transmit it

Is it possible to create a cookie in a textarea onkeypress and then send the cookie to a result page? Essentially, if the user types B or R in the textarea, can a cookie be created and sent to a result page? Below is the code snippet for each page: Exerci ...

Angular protection filter

Every time I used Angular CLI to generate a new component, it would create the component with standard parameters: @Component({ selector: 'app-test1', templateUrl: './test1.component.html', styleUrls: ['./test1.component.css ...