我想加载图像并根据图像尺寸调整画布大小。
当前,代码如下:
0
画布的定义如下:
canvas = null;
maxWidth = 800;
canvasWidth = 200;
canvasHeight = 200;
constructor() { }
loadImage(src) {
return new Promise((resolve, reject)=> {
console.log(src);
var img = new Image();
img.onload = () => resolve(img);
img.src = src;
});
}
ngOnInit() {
var src = "example_image_url";
this.canvas = document.getElementById('stage');
let ctx = this.canvas.getContext("2d");
this.loadImage(src).then(img => {
let width = img.width;
let height = img.height;
if (width > this.maxWidth) {
const scalingFactor = width / this.maxWidth;
width = this.maxWidth;
height /= scalingFactor;
this.canvasWidth = width;
this.canvasHeight = height;
}
ctx.drawImage(img,0,0, this.canvasWidth, this.canvasHeight);
});
}
加载图像后,它不可见。如果canvasWidth和canvasHeight不变,则显示图像。有谁知道如何正确加载图像并重新调整画布大小?
答案 0 :(得分:0)
不幸的是,您无法将Width和Height绑定到画布上,因为即使渲染this.canvasWidth
或this.canvasHeight
后渲染画布也不会对画布产生影响,因为您拥有ctx元素在您的角度范围内,您可以访问画布并更改其值,它将呈现您的图像
if (width > this.maxWidth) {
const scalingFactor = width / this.maxWidth;
width = this.maxWidth;
height /= scalingFactor;
ctx.canvas.width = width;
ctx.canvas.height = height;
}
ctx.drawImage(img,0,0, ctx.canvas.width, ctx.canvas.height);