问题
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