Reputation: 4912
I recently asked a question on how to draw an image larger than my canvas onto the canvas without cropping and save the image back into its original dimensions after performing some changes on it. I found the solution is to set the inline height
and width
attributes for the canvas larger than the image, and use css height
and width
properties to style the canvas to fit into your layout.
For example, assuming my images could range between 400px to 2000 px in dimensions. But I don't want the canvas to be so big, and I don't want the images to be cropped as well (because when saving the image with toDataURL
what is on the canvas is what is saved). This is what works:
//style
#mycanvas{
width: 400px;
height: 400px;
}
<canvas id="mycanvas" width="2000" height="2000" />
This works fine and my images come out well. But is this behavior buggy and bound to be changed/fixed in the future? I'm planning to use this solution for a task at hand.
Any guidance?
Upvotes: 5
Views: 4433
Reputation: 581
I know its been a long time since the question was asked, but I have another solution that can be used as well.
You can try using the canvasContext.drawImage() function, to resize the image as you draw the image into your canvas.
Syntax: void ctx.drawImage(image, dx, dy, dWidth, dHeight);
(If you know the size of the canvas and your image, you can calculate what these values need to be)
Upvotes: 0
Reputation: 154878
This behaviour is commonly used for controlling the size of a canvas:
See Canvas width and height in HTML5.
Upvotes: 6