I have a Canvas setup as follows:
<canvas id="canvas" style="width: 1200px; height: 500px;"></canvas>
I then want to upload a file and add it to the canvas, but drawn using a specific width and height, as follows:
var fileReader = new FileReader();
fileReader.onload = function( event ){
var image = new Image();
image.onload = function() {
canvasCtx.drawImage( image, 0, 0, 400, 200 );
};
image.src = event.target.result;
}
fileReader.readAsDataURL( file );
This image is added but it is using the full width and height of the canvas. I’ve tried scaling it, but can’t seem to get it working.
2
Answers
Canvas size is set by defining width and height properties:
That’s the size of two-dimensional context and you can draw on this canvas. It’s always in points. Otherwise you might use relative units, eg. percents:
How to draw on such canvas? How to determine where to put an image? That’s why there is a difference between how big is a drawing context, and how to place the canvas in webpage.
You can set the canvas to be 1200×500 and resize it to fit the parent container at the same time:
I hope it clears up your doubts.
drawImage method has 9 parameters.
You can stretch the image in given sizes like this:
Check https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage for more information.
Also, you should set width and height your canvas object for proper view. Proper code sample: