Canvas is unable to duplicate image content

I am trying to duplicate a PNG captcha image in order to remove its transparency so that the captcha resolver (ocrad.js) function can work properly.

However, I am facing an issue where the duplicated captcha image is being moved and resized.

How can I keep the dimensions of the captcha image unchanged?

I have attempted to set the canvas width to be equal to that of the image element, but it does not seem to resolve the issue.

function copy(pic) {

    var canvas = document.createElement('canvas');

    var context = canvas.getContext('2d');

    context.fillStyle = '#fff';  /// set white fill style
    context.fillRect(0, 0, canvas.width, canvas.height);

    context.drawImage(pic, pic.width, pic.height);
    var dataURL = canvas.toDataURL();
    document.getElementById('cimage').src = dataURL;

    alert(OCRAD(document.getElementById('cimage'))); //decode it
}

If you use the following code in Google Chrome's Console on this page, you will see that the Captcha image (in the center) moves, which is not the desired outcome:

pic = document.getElementById('cimage');
var canvas = document.createElement('canvas');

canvas.width = pic.width;
canvas.height = pic.height;

var context = canvas.getContext('2d');

context.fillStyle = '#fff';  /// set white fill style
context.fillRect(0, 0, canvas.width, canvas.height);

context.drawImage(pic, pic.width, pic.height);
var dataURL = canvas.toDataURL("image/jpeg");
document.getElementById('cimage').src = dataURL;

Answer №1

Make sure to set the size of the canvas element before drawing the image. By default, the element is set to 300x150 pixels:

var canvas = document.createElement('canvas');
canvas.width = pic.width;
canvas.height = pic.height;

Also, remember that drawImage requires the first two arguments for position, not size. Since the canvas is already the correct size with the code above, you just need to position the image at the origin (0,0):

context.drawImage(pic, 0, 0);

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

Encountered a Error: [$injector:modulerr] while integrating Angular JS with the mysterious Planet 9

I encountered an error after implementing AngularJS in Planet 9. Planet 9 is a tool built on top of SAP UI5, offering drag and drop functionality as well as the ability to include HTML, CSS, and JavaScript. I needed to use ng-repeat for an application, so ...

JavaScript's search function is encountering issues when working with multidimensional arrays

I have an array containing city names and postal codes that I need to search through. I can successfully search for the city name and retrieve the result, but when I try to search for a postal code, it doesn't register. My question is: How can I modif ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

Updating a boolean prop does not cause the child component to be refreshed

I am working with the following components: Parent: <template> <Child path="instance.json" v-bind:authenticated="authenticated" v-bind:authenticator="authenticator" /> </tem ...

Determine if the given text matches the name of the individual associated with a specific identification number

Struggling to create a validation system for two sets of fields. There are 6 inputs in total, with 3 designated for entering a name and the other 3 for an ID number. The validation rule is that if an input with name="RE_SignedByID" contains a value, then c ...

Discovering browser back button press event utilizing Angular

Can we identify when a user has navigated to a page using the browser's history back button? I am looking for a solution in angular.js without relying on angular routing. Additionally, it should also detect if a user returns to a form after submitting ...

Instructions for extracting the href value from an anchor tag using JavaScript within a specified string

How can I retrieve the href value of the last anchor tag in the provided content string using pure JavaScript, excluding jQuery? var contents = '<div id="content"><a href="http://www.okhype.com/wp-content/uploads/2016/12/ruffcoin-made-in-aba ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Utilizing async/await in React Redux for geolocation functionality

While attempting to retrieve the lng and lat by using geolocation with async and await, I encountered a situation where the promise was not awaited before it was passed to the reducer. Instead, another promise was returned. I had hoped that by using await ...

Discover the ins and outs of integrating YAML front matter into your destination directory path

I am looking to customize the path of my blog posts to include a fancy date format like /blog/2013/09/17 so that the links from my previous octopress blog remain intact. Within the YAML front matter on each markdown page, I have included the date informat ...

Encountering a 404 error when trying to click on 'allow' after using Firebase Cloud Messaging, and attempting to add a service worker manually proves unsuccessful in resolving the issue

Currently, I am working on integrating FCM (Firebase Cloud Messaging) into a React app. Initially, I tested it on a simple project without React and everything worked smoothly. However, implementing it in the React app has presented some challenges for me. ...

Observing a peculiar discrepancy in how various versions of JSON.stringify are implemented

Imagine having a deeply nested JS object like the example below that needs to be JSON-encoded: var foo = { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ {"id": 1, "name": "Name A", " ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Problems with the navigation bar scrolling in Bootstrap

The project I'm currently working on is located at zarwanhashem.com If you'd like to see my previous question along with the code, you can check it out here: Bootstrap one page website theme formatting problems Although the selected answer help ...

The metro bundler is facing an unexpected glitch and is stuck in the terminal, failing to load

Recently, I've been using explo-cli to work on a react native project. Everything was running smoothly until today when I encountered an error stating that it couldn't find module './iter-step'. Before this, there was also an issue with ...

Mastering the art of jQuery scrolling: A step-by-step guide

Is there a way to utilize jQuery for scrolling purposes? For example, transforming this: <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#home">Home <span class="sr-only">(current)</span></a> ...

What are some alternative ways to redirect multiple pages in a Navbar component in React Js without encountering the 'useNavigate()' error?

How can I resolve this error while working with react js? Error: useNavigate() is only allowed within a <Router> component. ▶ 3 stack frames were collapsed. Navbar C:/Users/dell/OneDrive/Desktop/ReactJs/react-learning/src/components/Navbar.js:9 ...

Using JQUERY to toggle classes conditionally

$('.showall').css("cursor","pointer").click(function() { $('.value-container').toggle(); $('.dim-header').toggleClass($('.dim-header').toggleClass() == 'dim-header' ? 'dim-header active' : & ...

The Meteor Call object stands apart from the Meteor Method object that was received

When I send an object from the client to the server using a Meteor Call and Meteor method, something strange happens. The object is received in the Method but it looks different - nested within the giftList. Meteor Call - JSON.stringify {"personName& ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...