如何用红色块绘制图像

时间:2018-12-15 03:28:35

标签: javascript canvas

图像上的红色块,大小为50*50,图像原点大小为320*180,图像元素大小为200*113

现在我想获得红色方块并在画布上绘制,但是我不知道如何计算,请告诉我whyhow

我的示例代码在这里

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;
  console.log(ratio, heightRatio, canvasRatio);
  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);
};
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" />

1 个答案:

答案 0 :(得分:2)

您需要使用长版本的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" />