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

Leveraging the "dialogclose" event within jQuery Mobile

Is there a way to change an image once it is clicked and change back when the dialog it links to is closed? I found a potential solution on this site, but after modifying it for my needs, it doesn't seem to work. Can anyone help me figure out what I a ...

What is the process for retrieving User Information using AngularJS following NodeJS authentication?

While I've come across similar questions on this topic, my lack of experience with Angular and Node is making it difficult for me to find a suitable solution. I had previously written this code that successfully handled the login process and allowed ...

What is the best way to incorporate a popover into a fullcalendar event displayed on a resource timeline in Vue while utilizing BootstrapVue?

I need help adding a popover to an event in a resource timeline using fullcalendar/vue ^5.3.1 in Vue ^2.6.11 with ^2.1.0 of bootstrap-vue. Although I found some guidance on Stack Overflow, the solution involving propsData and .$mount() doesn't feel l ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

I am encountering an issue while trying to update SQL data from within a Node.js

Using a for-loop to update SQL command is common practice. Here's an example: for(var i=count1; i < count2;i++){ Book.TimeStart = Times[I] console.log(Book.TimeStart) sql = sql + `UPDATE projectroom.Details SET BookingId = `+Book.Bo ...

Display the picture for a few moments, then conceal it. A button will appear to reveal the following image after a short period

For my project, I want to create a webpage for school where I display one image that disappears after 5 seconds, followed by a button. The user must click the button before the next image appears and stays for another 5 seconds. This sequence repeats each ...

What is the best way to send additional data with getServerSideProps() in Next.js?

Not sure if this is a silly question, but I am currently working with a Django API and attempting to implement pagination on the search page using Next.js. As a newbie to Next.js, I have scoured the web for a solution but haven't found anything helpfu ...

A small computation

How can I modify this code to calculate the total price #ttc by multiplying #totalcout with #marge Currently, I am able to add amounts when checkboxes are clicked, but I am struggling with integrating the multiplication for calculating the Total Price (TT ...

What could be the reason for the empty array returned by the combinationSum function in Javascript?

The combinationSum function is returning an empty resultArr. When checking the ds array with console.log, it shows the correct answer, but for some reason, the final output array ends up being [[],[]]. var combinationSum = function(candidates, target) { ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Issue with VueJS where the datalist input does not reset the value

I am currently working on a Vue component that scans QR codes and adds information to a database upon successful scanning. The scanning process works perfectly fine. However, after successfully sending the data, I need to clear the input field in my datali ...

Exploring discrepancies in JSON arrays using Lodash

Using lodash to find the difference between two arrays: c1Arr contains: [ { varName: 'city', varValue: 'cccccccc' }, { varName: 'country', varValue: 'dddddddd' } ] c2Arr contains: [ { varName: 'abc', ...

Printing without sufficient paper will result in an incomplete printout

https://i.stack.imgur.com/jNlRr.jpg I am facing an issue with printing the last column "Potensi". The text in this column is not fully printed. How can I resolve this problem? I am using PHP. Thank you ...

Creating Vue components and including Javascript code within them

Attempting to develop a component using Vue for my JavaScript code, but encountering issues. My primary aim is to build a component with either Vue or Vue3 <head> <title></title> <script src="https://cdn.jsdelivr ...

The onPress function seems to be malfunctioning within the menu interface specifically on iOS devices

I am experiencing an issue where a problem only occurs on iOS devices, but Android works fine. My menu has a userMenu class. import Menu, {MenuItem, MenuDivider} from 'react-native-material-menu'; class UserMenu extends React.Component { ...

Ways to iterate through a JSON formatted array variable using JavaScript

Below is my code snippet, used to plot all the locations fetched from my database onto a Google map. $.ajax({ url:"http://localhost/church_finder/index.php/MapController/search_church", type:'POST', data: ...

Error message stating that the function "data.map" is not recognized, resulting in a

const ShoppingList = ({ itemList }) => { let { loading, items } = itemList; console.log(items); return ( <div> {loading ? ( <p>Loading...</p> ) : ( <table> <thead> ...

The data is not appearing in the Vuetify data table

I have encountered an issue with the Vuetify data table where it is not displaying any data. Even though it shows that there is 1 row out of 1 displayed, the table body remains empty. Below is my component code: <template> <v-data-table :hea ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...