HTML5 Resize Image In Canvas

HTML5 Resize Image in Canvas

To upload and resize image in canvas is possible using HTML5 canvas object and canvas context drawImage() method with additional parameters. context.drawImage() draw a resized image object in canvas using the arguments passed during HTML5 method call.

HTML5 Canvas provides web developers a space to draw using Javascript with HTML5 APIs. This provides a flash style animation area where all drawing and animation is managed by scripting in HTML5 codes.

Here is how HTML5 Canvas object method drawImage() is used to resize image in canvas element. The first argument is the image object itself. It can be a URL address where you want to read and load image into canvas. x-coordinate and y-coordinate values are integer and points to the place where image will be displayed at referencing the top-left corner of the canvas element. resized-width and resized-height parameters are also in integer and represent the new width, height dimensions of the resized image. Or simply the target dimensions of the original image after resize operation.

context.drawImage(imageObject, x-coordinate, y-coordinate, resized-width, resized-height);
Code

Below HTML developers can find Javascript codes to upload and resize image in Canvas element at the same time.

<script> function resizeImage() { var canvas = document.getElementById("html5canvas"); var context = canvas.getContext("2d"); var resizedImageObj = new Image(); resizedImageObj.src = "/images/windows-8-screenshots/consumer-beta-windows-8-start-screen.png"; resizedImageObj.onload = function () { context.drawImage(resizedImageObj, 30, 10, 200, 150); }; } </script> <article> <button onclick="resizeImage();return false;">Resize Image in HTML5 Canvas</button><br /> <canvas id="html5canvas" width="300px" height="300px"></canvas> </article>
Code

And here in this HTML5 canvas tutorial, you can test the above code with below test case.

Press button to upload and resize image in canvas element: HTML5 Resize Image in Canvas

Your browser does not support HTML5 Canvas feature. Please check updates of your favorite web browser or try an other browser with HTML5 browser support. You can review HTML5 Browser Test scores

HTML5 programmers can also refer to HTML5 Canvas load image for an other HTML5 canvas tutorial on context.drawImage() method.

Từ khóa » Html Canvas Stretch Image