Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - Center Image inside canvas element

I'm scaling the image down so it fits inside the canvas, the thing I am struggling to do is to then center it inside of the canavas element, does anyone know how this could be done please? Any help would be appreciated

https://jsfiddle.net/n7xL5c37/

var canvas = document.getElementById('canvas');
var image = new Image();
    image.src = 'http://placehold.it/300x550';
    image.onload = function () {
        var canvasContext = canvas.getContext('2d');
        var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
                    newHeight = canvas.height;
            newWidth = newHeight * wrh;
        }

        canvasContext.drawImage(image,0,0, newWidth , newHeight);
      };
like image 303
NoDachi Avatar asked Sep 21 '16 14:09

NoDachi


People also ask

How do I center an image in canvas?

3. Click the "Align vertical centers" button on the Options toolbar to align each layer vertically on the canvas. If you do not have the Options toolbar open, click "Layer" on the menu, point to "Align Layers to Selection" and then click "Vertical Centers."

How do I center a canvas in a div?

To center canvas in HTML 5, include the canvas tag in div tag. Then we can center align the div tag. By doing so, the canvas is also center aligned.

Does JavaScript work in canvas?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.


1 Answers

    var canvas = document.getElementById('canvas');
    var image = new Image();
    image.src = 'http://placehold.it/300x550';
    image.onload = function () {
        var canvasContext = canvas.getContext('2d');
        var wrh = image.width / image.height;
        var newWidth = canvas.width;
        var newHeight = newWidth / wrh;
        if (newHeight > canvas.height) {
					newHeight = canvas.height;
        	newWidth = newHeight * wrh;
      	}
        var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
        var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;

      	canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
      };
<canvas id="canvas" width="500" height="500" style="border: 1px solid black" />
like image 185
Passersby Avatar answered Sep 26 '22 05:09

Passersby