Ols
Ols

Reputation: 41

How to center the image inside of canvas in javascript?

I have a problem with centring the image inside of the canvas. Canvas has to be full sized. The whole thing should create a web preloader. Styling image inside of css does not work in this case.

<style> canvas{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #000000;
    z-index: 99;   }

</style>   <body>
    <canvas id="c"><img id="logo" width="800" height="150" src="imgsource" alt="logo"></canvas> <div>   web content </div>

    <script>

    jQuery(window).on('load', function() { 
    jQuery('#c').delay(7000).fadeOut('slow'); 
    jQuery('body').delay(7000).css({'overflow':'visible'});
    })


    window.onload = function() {
        var c = document.getElementById("c");
        var ctx = c.getContext("2d");
        var img = document.getElementById("logo");
        ctx.drawImage(img, 50, 0);


    } </script>

Upvotes: 0

Views: 2822

Answers (2)

Narek Grigoryan
Narek Grigoryan

Reputation: 449

   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" />

Upvotes: 0

ASDFGerte
ASDFGerte

Reputation: 5195

The following only demonstrates the centering of an image inside a canvas with drawImg. Note that the image to the left is from the html <img> element while the other is from the drawImg call.

Outside of stackoverflow you'd have to wait for the image to load before drawing it, but as you also already use .on('load', ...) i assume you are aware of that.

To avoid having two images, create the image element in javascript and don't add it to the document but only use it for rendering.

let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
let img = document.getElementById("i");

//just to make the area the canvas occupies visible
ctx.fillStyle = 'grey';
ctx.fillRect(0, 0, canvas.width, canvas.height);

//draw the image centered
ctx.drawImage(
  img,
  canvas.width / 2 - img.width / 2,
  canvas.height / 2 - img.height / 2
);
<html>
  <body>
    <img id="i" src="http://i.imgur.com/kdJicdy.png"/>
    <canvas id="canvas" width="320" height="240">Your browser doesn't support canvas</canvas>
  </body>
</html>

Upvotes: 1

Related Questions