Having trouble with JavaScript canvas drawImage function not functioning correctly

Having some trouble drawing part of an image properly. The width and height are not matching the original.

Check out my code below:

window.onload = function() {
ImageObjSketch = new Image(); // URL
ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';

canvasClone = document.getElementById("squareTarget");
ctxClone = canvasClone.getContext("2d");
ctxClone.drawImage(ImageObjSketch,34,119,16,16,0,0,38,38);
}
#squareTarget {
width: 38px; height: 38px;
position: relative;
right: 0px;
display: inline-block;
border: 1px #000000 solid;
}
<canvas id="squareTarget"></canvas>

The square size is not proportional to the image, even though I specified a full size.

Also, why does this code need to be run twice in order to see the image?

Answer №1

If you want to create a canvas, it's important to define its size explicitly before accessing the 2D Context:

window.onload = function() {
var ImageObjSketch = new Image(); // URL
ImageObjSketch.src = 'https://i.imgur.com/75lATF9.png';

var canvasClone = document.getElementById("squareTarget");
canvasClone.width = 38;
canvasClone.height = 38;
ctxClone = canvasClone.getContext("2d");


ctxClone.drawImage(ImageObjSketch, 34,119,16,16,0,0,38,38);
}

Instead of hardcoding the size as 38, consider using the document's height and width for better flexibility:

ctxClone.drawImage(ImageObjSketch, 34,119,16,16,0,0,canvasClone.width,canvasClone.height);

Check out this CodePen link for a live demonstration.

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

Next.js encountered an issue with the element type, as it expected either a string for built-in components or a class/function for composite components, but received undefined instead

Recently, while working with next js, I encountered an issue when trying to import a rich text editor into my project. Specifically, when attempting to integrate react-draft-wysiwyg, an error message was displayed: Error: Element type is invalid... (full e ...

Issue arises when attempting to render a component while utilizing window.location.pathname and window.location.hash in conjunction with a navigation bar

I am encountering a problem when attempting to render a react component using a navigation bar. I have experimented with both Switch case and if-statement methods. The first approach involves using window.location.hash, which successfully alters the URL u ...

Improprove the design of the dropdown component using React

One of the challenges I am facing in my project is using multiple dropdowns from semantic-ui-react. Each dropdown needs to have different props, making the code look like this: <div className="wrapper"> <img className="icon" src={iconA} ...

I tried setting ajax async to false, but it doesn't seem to be functioning

I've been attempting to retrieve JSON data from another domain, and my code looks like this: var token = ''; function fetchData(){ console.log("Data fetched successfully"); for (var i=0; i < urls.length; i++){ var endpoint = &ap ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

Tips for implementing validations on a table that changes dynamically

I encountered an issue in my code while working on a dynamic form for age with unobtrusive client-side validation. The problem is that the validation is row-wise, but it behaves incorrectly by removing other rows' validations when I change one. Below ...

Tips on hiding specific table rows in two separate tables based on the chosen option from a dropdown menu

How do I hide table rows based on dropdown selection? The first table has a dropdown with two options: Current State and Future State. If I select Current State, I want to show or hide specific rows in the 2nd and 3rd tables. I am using IDs for these row ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

Reasons for the failure of file uploads from the React frontend to the backend system

Recently, I embarked on a new project that involves using React for the front-end and Node for the back-end. The main requirement of this project is to upload multiple images from the front-end, with the back-end handling the file uploads to Cloudinary. I ...

Stopping a file transfer in case of browser closure or upload cancellation

When working on uploading a file asynchronously using HTML5 in MVC3, a common issue arises when dealing with large files such as 1GB. If the upload process is cancelled or the browser is closed at 50% completion, a 500MB file still gets saved in the target ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

What is the process of uploading a video and showcasing it on an HTML page?

I have successfully uploaded images and displayed them on an HTML page. Now, I am looking to do the same for videos. Here is my current code: $('#addPhotosBtn').click(function() { $(this).parents().find('#addPhotosInput').click(); }) ...

I am experiencing difficulty with loading the local images stored in the /public/images directory of my React app

I am currently working on a component called Portafolio.js where I am utilizing the map function to retrieve each object from a file named "trabajos.js" that contains all the objects with their respective properties. My goal is to display an image for each ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Despite my usage of className, I still encounter the error message "Error: Invalid DOM property `class`."

I am having trouble debugging this issue as I am unsure of the exact location of the error. Here is the link to the repository: https://github.com/kstaver/React-Portfolio Error #2. There are three more promise rejection errors present, which I will addres ...

When defining multiple types for props in Vue, the default behavior for Boolean type props is not preserved

Imagine you have a component called MyComponent with a prop named myProp declared as: props: { myProp: Boolean } By simply using <MyComponent myProp/>, the default behavior would set myProp to true. However, this simplicity is lost when there ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...