我正在尝试加载图像,然后将其绘制到画布上,但目前我仅设法渲染一半图像:
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';
有人看到以上内容有什么问题吗?任何建议都将非常有帮助!
答案 0 :(得分:1)
因为画布尺寸小于图像
只需将画布大小设置为所需的大小,就可以看到所有图像。
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';
顺便说一句,您可以在CSS中设置尺寸,而您仍然具有相同的画布尺寸(css只是将其拉伸)。
//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;}