Вам нужно использовать длинную версию ctx.drawImage(image, sx, sy, swidth, sheight, dx, dy, dwidth, dheight)
, чтобы иметь возможность обрезать и изменять размер исходного изображения.
Версия с короткими 2 аргументами просто рисует исходное изображение в оригинальном размере с некоторым смещением по месту назначения, но вам также необходимо применить изменение размера к вашему выводу.
Так что используядлинную версию вы можете сделать
ctx.drawImage(img,
// source
x * ratioW,
y * ratioH,
width * ratioW,
height * ratioH,
// destination
0,
0,
width,
height
);
window.onload = function() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
const ratio = naturalWidth / img.offsetWidth;
const heightRatio = naturalHeight / img.offsetHeight;
const canvasRatio = naturalWidth / c.width;
const canvasYRatio = naturalHeight / c.height;
const r = 1/(naturalWidth/naturalHeight);
console.log(r);
const width = 50;
const height = 50;
const top = 50 * heightRatio;
const left = 90 * ratio;
ctx.drawImage(
img,
left, top, width * ratio, height * heightRatio,
0, 0, width, height
);
};
body{
position: relative;
}
<img id="scream" src="https://img.youtube.com/vi/uwMQRAC1JE8/mqdefault.jpg" alt="The Scream" width="200">
<div style="
position: absolute;
left: 90px;
top: 50px;
width: 50px;
height: 50px;
border: 1px solid red;
"></div>
<canvas id="myCanvas" width="50" height="50" style="border:1px solid #d3d3d3;display:block" />