ctx.drawImage only drawing half of image

后端 未结 1 1253
清酒与你
清酒与你 2021-01-24 00:07

I\'m trying to load an image then draw it to a canvas, but I\'m only managing to render half of the image presently:

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-24 00:46

    Because the canvas size is smaller than image

    Simply set the canvas size to what you need and you can see all of the image.

    let image = new Image();
    image.crossOrigin = 'Anonymous';
    image.onload = function() {
      let canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      let ctx = canvas.getContext('2d');
      ctx.drawImage(image, 0, 0);
      document.body.appendChild(canvas);
    }
    image.src = 'https://s3.amazonaws.com/duhaime/blog/visualizations/word-to-viz/heightmap.jpg';


    By the way, you can set the size in css and you still have the same canvas size (css just stretch it).

    //same code above
    let image = new Image();
    image.crossOrigin = 'Anonymous';
    image.onload = function() {
      let canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      let ctx = canvas.getContext('2d');
      ctx.drawImage(image, 0, 0);
      document.body.appendChild(canvas);
    }
    image.src = 'https://s3.amazonaws.com/duhaime/blog/visualizations/word-to-viz/heightmap.jpg';
    canvas{width:200px; height:100px;}

    0 讨论(0)
提交回复
热议问题