动态加载图像到叠加画布并调整它们的大小



我有两个画布,它们是重叠的。现在我想要动态加载图像到画布中,并根据图像大小调整它们的大小。

我现在的问题是,在画布加载图像并调整它们的大小后,它们覆盖了下面所有其他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>

按下"加载内容"后按钮,按钮不能向下移动。

我也尝试改变"container"的宽度和高度属性。,但行为没有改变。

我错过了什么?

所以,代码有很多问题。如果你是初学者,不要担心。这是正常的。☺

首先,<canvas>是对标记. 这意味着你必须用</canvas>关闭它。正确的形式是<canvas someattribute="somevalue"></canvas>。在<canvas>标签内部是替代内容的地方,当浏览器不支持<canvas>标签(它是相当新的)时将使用。

省略</canvas>打破了页面。

HTML规定了哪些标签必须关闭,哪些不应该关闭,<canvas>必须关闭的标签之一被关闭。Validator可以帮助您识别代码中的错误。请注意,这是相当迂腐的。

第二个问题是,你使用的是绝对定位和画布,当调整大小,覆盖按钮. 只需禁用定位或使用更精确的定位方式。第三个选择是在JS中适当地调整容器div的大小。

容器div也设置了固定的大小。默认情况下,当内容较大时,溢出.

你可能试图用z-index来解决它。设置z索引通常非常棘手,我尝试将其作为最后的手段。您的z-index属性都无效。z-index: NUMBER,而不是z- indexz index

我发现的最后一个bug是您在第二个函数中使用canvas1(未定义变量)而不是canvas

loadimage.onclick = function(e) {
//load image1
var img1 = new Image();
img1.onload = function() {
var canvas = document.getElementById("canvas1");
var ctx = canvas1.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, 0, 0);
};
img2.src = "https://via.placeholder.com/50/00FF00/808080/";
}
<div id="container">
<canvas id="canvas1" width="200" height="100" style="border: 1px solid #000;"></canvas>
<canvas id="canvas2" width="200" height="100" style="border: 1px solid #000;"></canvas>
</div>
<button id="loadimage" type="button">Load Content</button>

最新更新