Ark*_*lys 3 javascript css background-position
我正在尝试使用background-position和 百分比值制作一个简单的可拖动背景。到目前为止,我设法使拖动工作正常,但我似乎无法找到图像以相同速度跟随光标的正确计算(如果有意义的话)。
这是一个简单的示例(仅使用x轴):
const container = document.querySelector('div');
const containerSize = container.getBoundingClientRect();
let imagePosition = { x: 50, y: 50 };
let cursorPosBefore = { x: 0, y: 0 };
let imagePosBefore = null;
let imagePosAfter = imagePosition;
container.addEventListener('mousedown', function(event) {
cursorPosBefore = { x: event.clientX, y: event.clientY };
imagePosBefore = imagePosAfter; // Get current image position
});
container.addEventListener('mousemove', function(event) {
if (event.buttons === 0) return;
let newXPos = imagePosBefore.x + ((cursorPosBefore.x - event.clientX) * 100 / containerSize.width);
newXPos = (newXPos < 0) ? 0 : (newXPos > 100) ? 100 : newXPos; // Stop at the end of the image
imagePosAfter = { x: newXPos, y: imagePosition.y }; // Save position
container.style.backgroundPosition = `${newXPos}% ${imagePosition.y}%`;
});Run Code Online (Sandbox Code Playgroud)
div {
width: 400px;
height: 400px;
background-position: 50% 50%;
background-size: cover;
background-repeat: no-repeat;
background-image: url('https://i.stack.imgur.com/5yqL8.png');
cursor: move;
border: 2px solid transparent;
}
div:active {
border-color: red;
}Run Code Online (Sandbox Code Playgroud)
<div></div>Run Code Online (Sandbox Code Playgroud)
如果我单击背景上的白色十字之一并移动鼠标,则十字应始终保留在光标下方,直到到达图像的末尾或容器的末尾。
这可能只是一个数学问题,但我有点困惑,因为百分比如何与background-position. 任何想法?
我不知道公式到底是怎样的,但你也必须包括 css 背景的大小。
如果背景大小是容器 div 大小的 100%,则您的公式将有效,但事实并非如此。您需要知道缩放级别(可以根据与 div 大小相关的大小来计算)。
以下是当您拥有缩放级别时的公式:
container.addEventListener('mousemove', function(event) {
event.preventDefault();
const zoomAffector = (currentZoomLevel - 100) / 100; // 100% zoom = image as big as container
if (zoomAffector <= 0) return; // Cant drag a image that is zoomed out
let newXPos = imagePosBefore.x + ((imagePosBefore.x - event.pageX) / zoomAffector * 100;);
newXPos = (newXPos < 0) ? 0 : (newXPos > 100) ? 100 : newXPos;
imagePosAfter = { x: newXPos, y: imagePosition.y };
container.style.backgroundPosition = `${newXPos}% ${imagePosition.y}%`;
});
Run Code Online (Sandbox Code Playgroud)
要获取 css 背景图像的大小,也许可以查看这个问题:使用 JavaScript 获取 CSS 背景图像的大小?
这是我对您的问题的尝试,使用链接问题的答案之一来获取图像宽度(也为 y 轴做了它,以完成):
container.addEventListener('mousemove', function(event) {
event.preventDefault();
const zoomAffector = (currentZoomLevel - 100) / 100; // 100% zoom = image as big as container
if (zoomAffector <= 0) return; // Cant drag a image that is zoomed out
let newXPos = imagePosBefore.x + ((imagePosBefore.x - event.pageX) / zoomAffector * 100;);
newXPos = (newXPos < 0) ? 0 : (newXPos > 100) ? 100 : newXPos;
imagePosAfter = { x: newXPos, y: imagePosition.y };
container.style.backgroundPosition = `${newXPos}% ${imagePosition.y}%`;
});
Run Code Online (Sandbox Code Playgroud)
const container = document.querySelector('div');
const containerSize = container.getBoundingClientRect();
let imagePosition = { x: 50, y: 50 };
let cursorPosBefore = { x: 0, y: 0 };
let imagePosBefore = null;
let imagePosAfter = imagePosition;
var actualImage = new Image();
actualImage.src = $('#img').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
const zoomX = this.width / containerSize.width - 1;
const zoomY = this.height / containerSize.height - 1;
container.addEventListener('mousedown', function(event) {
cursorPosBefore = { x: event.clientX, y: event.clientY };
imagePosBefore = imagePosAfter; // Get current image position
});
container.addEventListener('mousemove', function(event) {
event.preventDefault();
if (event.buttons === 0) return;
let newXPos = imagePosBefore.x + ((cursorPosBefore.x - event.clientX) / containerSize.width * 100 / zoomX);
newXPos = (newXPos < 0) ? 0 : (newXPos > 100) ? 100 : newXPos;
let newYPos = imagePosBefore.y + ((cursorPosBefore.y - event.clientY) / containerSize.height * 100 / zoomY);
newYPos = (newYPos < 0) ? 0 : (newYPos > 100) ? 100 : newYPos;
imagePosAfter = { x: newXPos, y: newYPos };
container.style.backgroundPosition = `${newXPos}% ${newYPos}%`;
});
}Run Code Online (Sandbox Code Playgroud)
#img {
width: 400px;
height: 200px;
background-position: 50% 50%;
background-image: url('https://i.stack.imgur.com/5yqL8.png');
cursor: move;
border: 2px solid transparent;
}
#img:active {
border-color: red;
}Run Code Online (Sandbox Code Playgroud)
或者稍微清理一下:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img"></div>Run Code Online (Sandbox Code Playgroud)
const container = document.querySelector('div');
const containerSize = container.getBoundingClientRect();
let imagePosition = { x: 50, y: 50 };
let cursorPosBefore = { x: 0, y: 0 };
let imagePosBefore = null;
let imagePosAfter = imagePosition;
// Helpers
const minMax = (pos) => (pos < 0) ? 0 : (pos > 100) ? 100 : pos;
const setNewCenter = (x, y) => {
imagePosAfter = { x: x, y: y };
container.style.backgroundPosition = `${x}% ${y}%`;
};
const getImageZoom = () => {
return new Promise((resolve, reject) => {
let actualImage = new Image();
actualImage.src = $('#img').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
actualImage.onload = function() {
resolve({
x: zoomX = this.width / containerSize.width - 1,
y: zoomY = this.height / containerSize.height - 1
});
}
});
}
const addEventListeners = (zoomLevels) => {container.addEventListener('mousedown', function(event) {
cursorPosBefore = { x: event.clientX, y: event.clientY };
imagePosBefore = imagePosAfter; // Get current image position
});
container.addEventListener('mousemove', function(event) {
event.preventDefault();
if (event.buttons === 0) return;
let newXPos = imagePosBefore.x + ((cursorPosBefore.x - event.clientX) / containerSize.width * 100 / zoomLevels.x);
let newYPos = imagePosBefore.y + ((cursorPosBefore.y - event.clientY) / containerSize.height * 100 / zoomLevels.y);
setNewCenter(minMax(newXPos), minMax(newYPos));
});
};
getImageZoom().then(zoom => addEventListeners(zoom));
Run Code Online (Sandbox Code Playgroud)
#img {
width: 400px;
height: 200px;
background-position: 50% 50%;
background-image: url('https://i.stack.imgur.com/5yqL8.png');
cursor: move;
border: 2px solid transparent;
}
#img:active {
border-color: red;
}Run Code Online (Sandbox Code Playgroud)
或者回答您的后续问题:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="img"></div>Run Code Online (Sandbox Code Playgroud)
const container = document.querySelector("div");
const containerSize = container.getBoundingClientRect();
let imagePosition = { x: 50, y: 50 };
let cursorPosBefore = { x: 0, y: 0 };
let imagePosBefore = null;
let imagePosAfter = imagePosition;
// Helpers
const minMax = (pos) => (pos < 0 ? 0 : pos > 100 ? 100 : pos);
const setNewCenter = (x, y) => {
imagePosAfter = { x: x, y: y };
container.style.backgroundPosition = `${x}% ${y}%`;
};
const getImageZoom = () => {
return new Promise((resolve, reject) => {
let actualImage = new Image();
actualImage.src = $("#img")
.css("background-image")
.replace(/"/g, "")
.replace(/url\(|\)$/gi, "");
actualImage.onload = function () {
const imgW = this.width,
imgH = this.height,
conW = containerSize.width,
conH = containerSize.height,
ratioW = imgW / conW,
ratioH = imgH / conH;
// Stretched to Height
if (ratioH < ratioW) {
resolve({
x: imgW / (conW * ratioH) - 1,
y: imgH / (conH * ratioH) - 1,
});
} else {
// Stretched to Width
resolve({
x: imgW / (conW * ratioW) - 1,
y: imgH / (conH * ratioW) - 1,
});
}
};
});
};
const addEventListeners = (zoomLevels) => {
container.addEventListener("mousedown", function (event) {
cursorPosBefore = { x: event.clientX, y: event.clientY };
imagePosBefore = imagePosAfter; // Get current image position
});
container.addEventListener("mousemove", function (event) {
event.preventDefault();
if (event.buttons === 0) return;
let newXPos =
imagePosBefore.x +
(((cursorPosBefore.x - event.clientX) / containerSize.width) * 100) /
zoomLevels.x;
let newYPos =
imagePosBefore.y +
(((cursorPosBefore.y - event.clientY) / containerSize.height) * 100) /
zoomLevels.y;
setNewCenter(minMax(newXPos), minMax(newYPos));
});
};
getImageZoom().then((zoom) => addEventListeners(zoom));Run Code Online (Sandbox Code Playgroud)
#img {
width: 400px;
height: 200px;
background-size: cover;
background-position: 50% 50%;
background-image: url('https://i.stack.imgur.com/5yqL8.png');
cursor: move;
}Run Code Online (Sandbox Code Playgroud)