如何在 canvas 元素内将图像置于另一图像之上

How to Center Image above another image inside canvas element

我正在尝试在 canvas 元素中的另一张图片上方添​​加图片

我想达到的目标:

这是我得到的:

images source: https://imgur.com/gallery/jaSdhQ9

这是我的代码:

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>

我想你要找的是 flex-box

#canvas{
  display:flex;
  justify-content: center;
  align-content: center;
}

Here 你可以阅读更多关于 flex-box

你可以这样设置 ctx.drawImage(draw,100,30,90,50 );

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,80,25,135,55 );




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

感谢@tokage-dizayn 和

我来到这段代码

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>