图片无法覆盖画布的整个区域

时间:2019-06-13 06:08:07

标签: javascript html5-canvas

我想将图像拉伸到画布的大小。但是图片使用的是原始尺寸,而不是画布的尺寸。欢迎提供帮助。

              var canvas = document.createElement("canvas");
              canvas.setAttribute("width", "100px");
              canvas.setAttribute("height", "180px");
              //alert(canvas.height);
              myImg.width = canvas.width;
              myImg.height = canvas.height;
              var ctx44 = canvas.getContext("2d");
              ctx44.drawImage(myImg, 0, 0, canvas.width, canvas.height,0,0,canvas.width,canvas.height); 
        // image gets displayed in its original size instead of taking the size of the canvas

1 个答案:

答案 0 :(得分:0)

drawImage的第二到第四参数代表 source 矩形。也就是说,在将图像应用于目标之前,将从其中裁剪的矩形调整为以下矩形中定义的矩形。

这是一个简单的演示:

var img = new Image();
img.onload = e => {
  const source = document.getElementById('source');
  const destination = document.getElementById('destination');
  const imgWIDTH = source.width = destination.width = 300;
  const imgHEIGHT = source.height = destination.height = 300;
  
  const src_x = source.getContext('2d');
  const dest_x = destination.getContext('2d');
  
  src_x.drawImage(img, 0, 0, imgWIDTH, imgHEIGHT); // simple copy to source canvas
  
  const source_rect = {
    x: 20,
    y: 20,
    w: 150,
    h: 150
  };
  const dest_rect = {
    x: 0,
    y: 0,
    w: 300,
    h: 300
  };
  
  destination.getContext('2d')
    .drawImage(source,
      source_rect.x,
      source_rect.y,
      source_rect.w,
      source_rect.h,
      dest_rect.x,
      dest_rect.y,
      dest_rect.w,
      dest_rect.h
    );
  
  // show the source rectangle on the 'source' canvas
  src_x.strokeRect(
    source_rect.x,
    source_rect.y,
    source_rect.w,
    source_rect.h,
  );
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png"
<canvas id="source"></canvas>
<canvas id="destination"></canvas>

因此,在您的情况下,如果原始图像小于画布的100x180px,则您将源矩形定义为在源图像之外,那么这将导致原始图像没有明显变化。

您可能想要的是

ctx44.drawImage(myImg, 0, 0, myImg.naturalWidth, myImg.naturalHeight,0,0,canvas.width,canvas.height);

与5参数版本相同

ctx44.drawImage(myImg,0,0,canvas.width,canvas.height);

var myImg = new Image();
myImg.onload = function(e) {
  var canvas = document.createElement("canvas");
  canvas.width = 100;
  canvas.height = 180;
  var ctx44 = canvas.getContext("2d");
  ctx44.drawImage(myImg, 0,0,canvas.width,canvas.height);
  document.body.appendChild(myImg);
  document.body.appendChild(canvas);
};
myImg.src = "https://i.stack.imgur.com/LbM0l.jpg?s=32&g=1"