ctx.drawImage only drawing half of image

旧时模样 提交于 2021-01-20 09:02:17

问题


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:

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

Does anyone see what's wrong with the above? Any suggestions would be very helpful!


回答1:


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;}


来源:https://stackoverflow.com/questions/55816610/ctx-drawimage-only-drawing-half-of-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!