【发布时间】:2021-09-10 23:47:38
【问题描述】:
我正在编写一个函数,该函数在容器 div 中添加图像(来自数组),位于用户在那一刻单击的坐标处。
问题是我不能保持容器尺寸固定,我不知道为什么每当我添加靠近其边界的图像时它会一直放大。
我面临的另一个问题是,除非我将它放在 div 中,否则我无法获得 img 高度,但我需要在创建图像时获得该信息,因为我需要将它放在中间点击点。
你能帮我弄清楚我做错了什么吗?
document.addEventListener('DOMContentLoaded', () => {
//setup variables
var arrayImgs = ['https://media-cdn.tripadvisor.com/media/photo-s/0e/eb/ad/3d/crazy-cat-cafe.jpg','https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Chairman_Meow_Bao.jpg/1200px-Chairman_Meow_Bao.jpg','https://static.scientificamerican.com/sciam/cache/file/92E141F8-36E4-4331-BB2EE42AC8674DD3_source.jpg','https://cdn.britannica.com/91/181391-050-1DA18304/cat-toes-paw-number-paws-tiger-tabby.jpg'];
var imgIndex = 0;
document.querySelectorAll('.container').forEach(trigger => {
trigger.addEventListener('click', function(){
if (imgIndex >= arrayImgs.length){
//check index to loop array
imgIndex = 0;
}
var imgToAdd = document.createElement("img");
var container = document.getElementById("myCanvas");
imgToAdd.setAttribute("src", arrayImgs[imgIndex]);
imgToAdd.classList.add('class-img');
var x = event.clientX;
var y = event.clientY;
//generate a random width form the image
var rndInt = Math.floor(Math.random() * 33) + 20;
var imgWidth = ((window.innerWidth / 100) * rndInt);
//parse image width
imgWidth = Math.floor(imgWidth);
imgToAdd.setAttribute("width", imgWidth );
imgToAdd.setAttribute("height", "auto" );
var imgHeight = imgToAdd.height;
//place the image in the middle of mouse X and Y
imgToAdd.style.position = "absolute";
imgToAdd.style.left = (x - (imgWidth / 2))+'px';
imgToAdd.style.top = (y - (imgWidth / 2))+'px';
container.appendChild(imgToAdd);
imgIndex = imgIndex + 1;
});
});
});
#myCanvas {
margin:0;
padding: 0;
width: 100%;
max-width: 100%;
max-height: 100vh;
height: 100vh;
box-sizing: border-box;
overflow: hidden;
}
*{
box-sizing: border-box;
padding: 0;
margin: 0;
}
.class-img {
overflow: hidden;
animation: bounce 1s;
-webkit-animation: bounce 1s;
-moz-animation: bounce 1s;
}
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"
/>
<div id="myCanvas" class="container">CLICK ME</div>
【问题讨论】:
标签: javascript html css canvas