0

I've a PNG captcha image and I want to create a duplicate so as to remove it's transparency because then the captcha resolver(ocrad.js) function works.

But the problem is that the following function is almost working properly but the captcha image gets moved and resized.

How to keep the captcha image's same dimension?

I've tried setting canvas width to same as that of img element, but does not work.

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
}

So if I enter the following code in Google Chrome's Console on this page, you'll see that Captcha image(in the center) moves somewhere which is what I don't want:

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;
user5858
  • 1,082
  • 4
  • 39
  • 79

1 Answers1

0

Set canvas element size before drawing the image. The element's default size is 300x150 pixels:

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

Additionally, you are using drawImage wrong - the two first arguments are for position, not size. As canvas is already the correct size using the code above, you just need to place the image at origin (0, 0):

context.drawImage(pic, 0, 0);