提问人:Onieone 提问时间:11/15/2023 更新时间:11/15/2023 访问量:28
如何在不使用 css 中的背景位置的情况下将背景缩放到中心点?
How can i zoom the background to the center point without using background position in css?
问:
Html 格式
<div class="board"></div>
JS 拖拽功能
var mouseProperties = {
mouseState: false,
prevX: null,
prevY: null,
}
var debugMode = {
appDebug: false,
isDrawEnabled: false,
isAnchorEnabled: false,
isEraserEnabled: false,
fpsAlreadyRunnin: false,
eraserRadius: 20,
}
// triggers when the mouse is pressing
document.addEventListener("mousedown", () => {
mouseProperties.mouseState = true;
});
// and triggers when mouse isn't pressing
document.addEventListener("mouseup", () => {
mouseProperties.mouseState = false;
mouseProperties.prevX = null;
mouseProperties.prevY = null;
});
//theres a mouse down eventlistener and an if state to check if mouse is pressing and if true then
//it will run the if below (debugmode is binded to a button in my html file it's not that important)
if (!debugMode.isDrawEnabled && !debugMode.isEraserEnabled) {
const currentX = e.screenX;
const currentY = e.screenY;
if (mouseProperties.prevX !== null && mouseProperties.prevY !== null) {
const deltaX = currentX - mouseProperties.prevX;
const deltaY = currentY - mouseProperties.prevY;
const lastPosX = parseInt(board.style.backgroundPositionX || 0);
const lastPosY = parseInt(board.style.backgroundPositionY || 0);
const anchedElements = document.querySelectorAll('.anch');
const bypassElements = document.querySelectorAll('.bypass');
anchedElements.forEach(nailed => {
const anchX = parseInt(nailed.style.left || 0);
const anchY = parseInt(nailed.style.top || 0);
nailed.style.left = `${anchX + deltaX}px`;
nailed.style.top = `${anchY + deltaY}px`;
});
board.style.backgroundPosition = `${lastPosX + deltaX}px ${lastPosY + deltaY}px`;
bypassElements.forEach((el) => observer.observe(el))
}
mouseProperties.prevX = currentX;
mouseProperties.prevY = currentY;
}
JS 缩放功能
const board = document.querySelector(".board")
var boardScale = 40
// unzoom
function unzoom() {
if (boardScale > 10) {
boardScale -= 5
} else if (boardScale < 10 || boardScale == 10) {
boardScale = 10
}
board.style.backgroundSize = `${boardScale}px ${boardScale}px`
}
// zoom
function zoom() {
if (boardScale < 70) {
boardScale += 5
} else if (boardScale > 70 || boardScale == 70) {
boardScale = 70
}
board.style.backgroundSize = `${boardScale}px ${boardScale}px`
}
这就是我遇到问题的地方。通常我更喜欢使用,但在我的项目中,我用它来拖动板背景,所以我不能使用它。我尝试了一些数学之类的东西,但它们也没有用。我试着缩放棋盘。当我缩放板时,它效果很好,但当我取消缩放时却没有。background-position: center center
当我拖动棋盘时,它会改变背景的中心,然后当我放大并且缩放在那个点上时。所以我试着用背景位置减去板的宽度和高度,但我做不到。
答: 暂无答案
评论