Search code examples
javascripthtmlcanvasandroid-canvas

How to Center Image above another image inside canvas element


I'm trying to add Images above another image in the canvas element

What I'm trying to reach:

What I'm trying to reach: Image above another image in the canvas element

Here is what I get:

Here is what I get

images source: https://i.sstatic.net/L1Dxu.jpg

and this my code:

var shirt = new Image();
shirt.src = "https://i.imgur.com/3rTZGXP.png";

var draw = new Image();
draw.src = "https://i.imgur.com/2abnbj1.png";
//draw.src = "https://i.imgur.com/TSJRGjo.png";




window.onload = function() {
var canvas = document.getElementById("canvas");

var ctx = canvas.getContext("2d");    
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);


ctx.drawImage(draw,0,0 );




ctx.drawImage(shirt,0,0,canvas.width,canvas.height);
}
#canvas{
    width: 352px;
    height: 448px; 
    left: 0px; 
    top: 0px; 
    user-select: none; 
    cursor: default;
}
<canvas id="canvas" width="352" height="448"></canvas>


Solution

  • thanks to @tokage-dizayn and https://stackoverflow.com/a/19473880/7511165

    I came to this code

    var shirt = new Image();
    shirt.src = "https://i.imgur.com/3rTZGXP.png";
    
    var draw = new Image();
    draw.src = "https://i.imgur.com/2abnbj1.png";
    //draw.src = "https://i.imgur.com/TSJRGjo.png";
    
    
    
    
    window.onload = function() {
      var canvas = document.getElementById("canvas");
    
        var ctx = canvas.getContext("2d");    
        ctx.fillStyle = "blue";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        console.log(draw.height,draw.width);
        
        var maxSize  = 160;
        var ratio = Math.min(maxSize  / draw.width, maxSize / draw.height);
        var width= draw.width*ratio, 
            height= draw.height*ratio;
        
        console.log(ratio,width,height);
    
            
        ctx.drawImage(draw,95,90,width,height);
        
        
        
        
        ctx.drawImage(shirt,0,0,canvas.width,canvas.height);
    }
    #canvas{
        width: 352px;
        height: 448px; 
        left: 0px; 
        top: 0px; 
        user-select: none; 
        cursor: default;
    }
    <canvas id="canvas" width="352" height="448"></canvas>