Равномерное увеличить div относительно его центра мышкой JS
Возник вопрос: как реализовать растяжение <div> относительно его центра.
Например, есть div в котором нарисован круг. Как сделать что бы при растяжке мишкой за край он растягивался относительно центра? HTML
<div id="app"></div>
CSS
#app {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
.circle {
position: absolute;
width: 10px;
height: 10px;
background: black;
border-radius: 100%;
z-index: 4;
}
JS
function BlueCircleRadius1(Xa, Ya, Xb, Yb) {
let radius = Math.sqrt(Math.pow(Xa - Xb, 2) + Math.pow(Ya - Yb, 2));
return radius;
}
const appDiv = document.querySelector("#app");
let count = 4;
class Circle {
constructor({ pageX, pageY, circleSize = 10 }) {
const element = document.createElement("div");
element.id = 5 - count;
element.className = "circle";
element.style.top = `${pageY - circleSize / 2}px`;
element.style.left = `${pageX - circleSize / 2}px`;
this.element = element;
}
draw = (container) => {
container.append(this.element);
};
}
appDiv.onmousedown = function (event) {
if (event.target.classList.contains("circle")) {
const ball = event.target;
function move(pageX, pageY) {
ball.style.left = pageX - ball.offsetWidth / 2 + "px";
ball.style.top = pageY - ball.offsetWidth / 2 + "px";
if (count == -1 && event.target.id == "1") {
var el1 = X1.value;
var numEl1 = parseInt(el1.match(/\d+/));
var el2 = Y1.value;
var numEl2 = parseInt(el2.match(/\d+/));
var el3 = X2.value;
var numEl3 = parseInt(el3.match(/\d+/));
var el4 = Y2.value;
var numEl4 = parseInt(el4.match(/\d+/));
let obj = document.getElementById("circleBlue");
let rad = BlueCircleRadius1(numEl1, numEl2, numEl3, numEl4);
obj.style.left =
pageX - Number.parseInt(obj.style.width) / 2 + "px";
obj.style.top =
pageY - Number.parseInt(obj.style.height) / 2 + "px";
obj.style.width = 2 * rad + "px";
obj.style.height = 2 * rad + "px";
}
if (count == -1 && event.target.id == "2") {
var el1 = X1.value;
var numEl1 = parseInt(el1.match(/\d+/));
var el2 = Y1.value;
var numEl2 = parseInt(el2.match(/\d+/));
var el3 = X2.value;
var numEl3 = parseInt(el3.match(/\d+/));
var el4 = Y2.value;
var numEl4 = parseInt(el4.match(/\d+/));
let obj = document.getElementById("circleBlue");
let rad = BlueCircleRadius1(numEl1, numEl2, numEl3, numEl4);
obj.style.width = 2 * rad + "px";
obj.style.height = 2 * rad + "px";
obj.style.left =
pageX - Number.parseInt(obj.style.height) / 2 + "px";
obj.style.top =
pageY - Number.parseInt(obj.style.width) / 2 + "px";
}
let X = document.getElementById(`X${event.target.id}`);
let Y = document.getElementById(`Y${event.target.id}`);
X.value = "left = " + " " + String(pageX - ball.offsetWidth / 2);
Y.value = "top = " + " " + String(pageY - ball.offsetWidth / 2);
}
function onMouseMove(event) {
move(event.pageX, event.pageY);
if (count == 0) {
console.log("Строй");
}
}
function mouseUp() {
document.removeEventListener("mousemove", onMouseMove);
}
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("mouseup", mouseUp, { once: true });
} else {
if (count > 0) {
let X = document.getElementById(`X${5 - count}`);
let Y = document.getElementById(`Y${5 - count}`);
X.value = "left = " + " " + String(event.pageX - 5);
Y.value = "top = " + " " + String(event.pageY - 5);
const { pageX, pageY } = event;
const circle = new Circle({ pageX, pageY });
circle.draw(appDiv);
count--;
}
if (count == 0) {
function BlueCircleRadius(Xa, Ya, Xb, Yb) {
let radius = Math.sqrt(
Math.pow(Xa - Xb, 2) + Math.pow(Ya - Yb, 2)
);
return radius;
}
function LargeBlueCircleDrawing(radius, Ax, Ay) {
let obj = document.getElementById("app");
let tmp;
tmp = document.createElement("div");
tmp.id = "circleBlue";
tmp.style.zIndex = 2;
tmp.style.height = 2 * radius + "px";
tmp.style.width = 2 * radius + "px";
tmp.style.borderRadius = "100%";
tmp.style.position = "absolute";
tmp.style.left = Ax - radius + 5 + "px";
tmp.style.top = Ay - radius + 5 + "px";
tmp.style.background = "blue";
obj.appendChild(tmp);
}
var el1 = X1.value;
var numEl1 = parseInt(el1.match(/\d+/));
var el2 = Y1.value;
var numEl2 = parseInt(el2.match(/\d+/));
var el3 = X2.value;
var numEl3 = parseInt(el3.match(/\d+/));
var el4 = Y2.value;
var numEl4 = parseInt(el4.match(/\d+/));
//console.log(numEl);
LargeBlueCircleDrawing(
BlueCircleRadius(numEl1, numEl2, numEl3, numEl4),
numEl1,
numEl2
);
count--;
}
}
};
Ответы (1 шт):
Автор решения: Armen
→ Ссылка
итак, код слишком жесткий, не смог разобратся + там ошибка есть(тоже не стал разбиратся).
вот рабочий вариант по оси Y(ось X сам доделаеш + появление круга или еще что там было у тебя)
кратко про логику, мы просто берем и каждый раз ресуем новый круг с новым размером вместо того чтобы менять его размер.
const app = document.querySelector('.app')
const appYCenter = Math.round(app.clientHeight / 2)
const appXCenter = Math.round(app.clientWidth / 2)
const createCircle = ({
container,
size,
left,
top,
}) => {
const circle = document.createElement('div')
const divideSize = size / 2
circle.style.position = 'absolute'
circle.style.width = `${size}px`
circle.style.height = `${size}px`
circle.style.border = '4px solid red'
circle.style.borderRadius = '50%'
circle.style.top = `${top - divideSize}px`
circle.style.left = `${left - divideSize}px`
createCircle.circle?.remove()
container.appendChild(circle)
createCircle.circle = circle
}
createCircle({
container: app,
size: 200,
left: appXCenter,
top: appYCenter,
})
app.addEventListener('mousemove', (e) => {
const borderSize = 4
const isUp = appYCenter > e.pageY
let size = isUp ? (appYCenter - e.pageY) * 2 : (e.pageY - appYCenter) * 2
createCircle({
container: app,
size: size - borderSize,
left: appXCenter,
top: appYCenter,
})
})
.app {
height: 100vh;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="app">
</div>
<script src="./main.js"></script>
</body>
</html>
если вдруг что то не получится дай знать, помогу разобратся.