【发布时间】:2025-12-15 11:30:01
【问题描述】:
我有两个重叠的画布。现在我想将图像动态加载到画布中,并根据图像大小调整它们的大小。
我现在的问题是,在画布加载图像并自行调整大小后,它们会覆盖下面的所有其他 html 项。
这是最简单的例子:
loadimage.onclick = function(e) {
//load image1
var img1 = new Image();
img1.onload = function() {
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
//resize canvas1
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 0, 0);
};
img1.src = "https://via.placeholder.com/250/0000FF/808080/";
//load image2
var img2 = new Image();
img2.onload = function() {
var canvas = document.getElementById("canvas2");
var ctx = canvas.getContext("2d");
//resize canvas1
canvas.width = this.naturalWidth;
canvas.height = this.naturalHeight;
ctx.drawImage(this, 75, 75);
};
img2.src = "https://via.placeholder.com/50/00FF00/808080/";
}
<div id="container" style="position: relative; width: 200px; height: 100px;">
<canvas id="canvas1" width="200" height="100" style="position: absolute; left: 0; top: 0; z-index: 0; border: 1px solid #000;"></canvas>
<canvas id="canvas2" width="200" height="100" style="position: absolute; left: 0; top: 0; z-index: 1; border: 1px solid #000;"></canvas>
</div>
<button id="loadimage" type="button">Load Content</button>
按下“加载内容”后 按钮,按钮不会向下移动。
我还尝试更改“容器”的宽度和高度属性 div,但行为没有改变。
我在这里错过了什么?
【问题讨论】:
-
你为什么使用画布?普通的
img/picture元素就足够了。 -
在我的原始代码中,我正在进一步处理画布中的图像(绘制、调整上层图像的大小等)
标签: javascript html css html5-canvas