【发布时间】:2019-10-23 18:46:31
【问题描述】:
我想加载图像并根据图像尺寸调整画布大小。
目前,代码如下:
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);
});
}
画布定义如下:
<canvas id="stage" [width]="canvasWidth" [height]="canvasHeight"></canvas>
加载图像时,它是不可见的。如果 canvasWidth 和 canvasHeight 不变,则显示图像。有谁知道如何正确加载图像并重新调整画布大小?
【问题讨论】:
-
我不会说它是重复的,因为建议的答案与 javascript 有关。我不确定这是特定于角度的问题还是由其他原因引起的。
标签: angular