Paul Tilman
Paul Tilman

Reputation: 21

Canvas image cropping issue. Is the image too big?

Yesterday, I already asked a question about this issue. I had no idea, however, what the problem was. Today I know it is something about the sourceWidth in the drawImage command:

context.drawImage(imageObj, sourceX, sourceY, sourceWidth,
        sourceHeight, destX, destY, destWidth, destHeight);

So I've descided to open a new topic and delete the old one.

But let me start at the beginning: I'm trying to implement a homemade "zoom function" on a historical document (see image below). It works fine in Firefox, but it does not in any other browser.

Firefox behaviour

In Chrome or Internet Explorer it looks like this. The zoom-area is empty.

Chrome behaviour

An image is displayed, if I just draw it, without any cropping:

context.drawImage(imageObj, 0, 0);

But if I try to use the crop function (explained at html5canvastutorials.com) with all needed values (sourceWidth = 1800), I cannot see the image in my canvas. Interestingly, if I change the sourceWidth to a low value like 400 or lower the image is drawn. An imageObj.onload doesn't change anything, as well as the adaption of the original image size (e.g. to 600x900) or the width of the canvas.

Upvotes: 1

Views: 3735

Answers (1)

Paul Tilman
Paul Tilman

Reputation: 21

I have figured out the solution for my problem. It's about the sourceWidth and the destX. I think it was a trivial problem, but I didn't know about this condition. It's about the following command:

context.drawImage(imageObj, sourceX, sourceY, sourceWidth,
        sourceHeight, destX, destY, destWidth, destHeight);

You have to make sure that imageWidth - destX = sourceWidth, if sourceWidth is greater, Chrome, IE ... won't draw your image. I don't know why Firefox can cope with it.

Here is a numerical example: imageWidth = 1024, you want to cut off 200px of the left side, so destX = 200 and sourceWidth < 824.

Upvotes: 1

Related Questions