Оцентровать изображение
Ребят, как оцентровать изображения когда перетягиваешь? Она сейчас цепляет с левого верхнего угла. Код некоторое подобие паззлов
index.html
<!DOCTYPE html>
<html>
<head>
<title>Пазлы УдГУ</title>
<script type="text/javascript" src="js/puzzleilnaz.js"></script>
<link rel="stylesheet" href="css/style.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var game = null;
var imageID = "img1";
var totalRows;
var totalColumns;
function InitGame() {
LoadNewImage(imageID);
}
function LoadNewImage(imgID) {
imageID = imgID;
totalRows = 3;
totalColumns = 3;
LoadGame();
}
function LoadGame() {
var canvasID = "puzz";
game = new pazzli(canvasID, imageID, totalRows, totalColumns);
game.initDrawing();
}
function ShowPreview() {
if (game) {
game.showPreview();
}
}
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
</head>
<body onload="InitGame();">
<table>
<tr>
<td>
<div>
<table cellpadding="0" cellspacing="0" width="100%">
<tr>
<td width="150px">
<span >
<input type="button" value="Показать картинку" onclick="ShowPreview()" />
</span>
</td>
</tr>
</table>
</div>
<div>
<canvas id="puzz" width="1000" height="575" style="border: black solid 2px;"></canvas>
</div>
</td>
<td width="20px">
</td>
<td style="vertical-align: top;">
<div align="right" style="height: 585px; width: 320px; border: black solid 1px; overflow: auto;">
<div>
<p>Выберите картинку</p>
<input type="file" onchange="previewFile()" multiple accept="image/*,image/jpeg"><br>
<p>Кликните по картинке 2 раза, чтобы активировать пазл</p>
<img id="img1" width="300" height="200" ondblclick="LoadNewImage(this.id);" src="Images/BugsLife.jpg"></img>
</div>
</div>
</td>
</tr>
</table>
<div class="footer"><img src="Images/logo_udsu.png" alt="Udsu" width="32" height="32"></div>
</body>
</html>
|
puzzleilnaz.js
function imageBlock(no, x, y) {
this.no = no;
this.x = x;
this.y = y;
this.isSelected = false;
}
function pazzli(canvasID, imageID, rows,columns) {
var MAIN_IMG_WIDTH = 800;
var MAIN_IMG_HEIGHT = 600;
var BLOCK_IMG_WIDTH = 600;
var BLOCK_IMG_HEIGHT = 450;
var TOTAL_ROWS = rows;// 4;
var TOTAL_COLUMNS = columns; //4;
var TOTAL_PIECES = TOTAL_ROWS * TOTAL_COLUMNS;
var IMG_WIDTH = Math.round(MAIN_IMG_WIDTH / TOTAL_COLUMNS);
var IMG_HEIGHT = Math.round(MAIN_IMG_HEIGHT / TOTAL_ROWS);
var BLOCK_WIDTH = 0;
var BLOCK_HEIGHT = 0;
var image1;
var canvas;
var ctx;
this.canvasID = canvasID;
this.imageID = imageID;
this.top = 0;
this.left = 0;
this.imageBlockList = new Array();
this.blockList = new Array();
this.selectedBlock = null;
this.mySelf = this;
this.initDrawing = function () {
mySelf = this;
selectedBlock = null;
canvas = document.getElementById(canvasID);
ctx = canvas.getContext('2d');
//canvas.ondblclick = handleOnMouseDbClick;
canvas.onmousedown = rykaOnMouseDown;
canvas.onmouseup = rykaOnMouseUp;
canvas.onmouseout = rykaOnMouseOut;
canvas.onmousemove = rykaOnMouseMove;
image1 = document.getElementById(imageID);
initializeNewGame();
};
function initializeNewGame() {
// Задается блок
BLOCK_WIDTH = Math.round(BLOCK_IMG_WIDTH / TOTAL_COLUMNS);
BLOCK_HEIGHT = Math.round(BLOCK_IMG_HEIGHT / TOTAL_ROWS);
// Рисуется картинка
SetImageBlock();
DrawGame();
}
this.showPreview = function () {
var x1 = 20;
var y1 = 20;
var width = BLOCK_IMG_WIDTH - (x1 * 2);
var height = BLOCK_IMG_HEIGHT - (y1 * 2);
ctx.save();
ctx.drawImage(image1, 0, 0, MAIN_IMG_WIDTH, MAIN_IMG_HEIGHT, x1, y1, width, height);
// Прямоугольник рядом с картинкой
ctx.fillStyle = '#00f'; // синий
ctx.strokeStyle = '#ffff00'; // жетый
ctx.lineWidth = 4;
ctx.strokeRect(x1 - 2, y1 - 2, width + 4, height + 4);
ctx.restore();
};
function DrawGame() {
clear(ctx);
drawLines();
drawAllImages();
if (selectedBlock) {
drawImageBlock(selectedBlock);
}
}
function SetImageBlock() {
var total = TOTAL_PIECES;
imageBlockList = new Array();
blockList = new Array();
var x1 = BLOCK_IMG_WIDTH + 20;
var x2 = canvas.width - 50;
var y2 = BLOCK_IMG_HEIGHT;
for (var i = 0; i < total; i++) {
var randomX = randomXtoY(x1, x2, 2);
var randomY = randomXtoY(0, y2, 2);
var imgBlock = new imageBlock(i, randomX, randomY);
imageBlockList.push(imgBlock);
var x = (i % TOTAL_COLUMNS) * BLOCK_WIDTH;
var y = Math.floor(i / TOTAL_COLUMNS) * BLOCK_HEIGHT;
var block = new imageBlock(i, x, y);
blockList.push(block);
}
}
//Само поле
function drawLines() {
ctx.strokeStyle = "#985cff";
ctx.lineWidth = 1;
ctx.beginPath();
// Вертикальные линии
for (var i = 0; i <= TOTAL_COLUMNS; i++) {
var x = BLOCK_WIDTH * i;
ctx.moveTo(x, 0);
ctx.lineTo(x, 450);
}
// Горизонтальные линии
for (var i = 0; i <= TOTAL_ROWS; i++) {
var y = BLOCK_HEIGHT * i;
ctx.moveTo(0, y);
ctx.lineTo(600, y);
}
ctx.closePath();
ctx.stroke();
}
function drawAllImages() {
for (var i = 0; i < imageBlockList.length; i++) {
var imgBlock = imageBlockList[i];
if (imgBlock.isSelected == false) {
drawImageBlock(imgBlock);
}
}
}
function drawImageBlock(imgBlock) {
drawFinalImage(imgBlock.no, imgBlock.x, imgBlock.y, BLOCK_WIDTH, BLOCK_HEIGHT);
}
function drawFinalImage(index, destX, destY, destWidth, destHeight) {
ctx.save();
var srcX = (index % TOTAL_COLUMNS) * IMG_WIDTH;
var srcY = Math.floor(index / TOTAL_COLUMNS) * IMG_HEIGHT;
ctx.drawImage(image1, srcX, srcY, IMG_WIDTH, IMG_HEIGHT, destX, destY, destWidth, destHeight);
ctx.restore();
}
function drawImage(image) {
ctx.save();
ctx.drawImage(image, 0, 0, BLOCK_WIDTH, BLOCK_WIDTH, 10, 10, BLOCK_WIDTH, BLOCK_WIDTH);
ctx.restore();
}
var interval = null;
var remove_width;
var remove_height;
function OnFinished() {
alert("УРРА!!! Пазл собран. Пока с Alert'ом, можно сделать со звуком.");
remove_width = BLOCK_WIDTH;
remove_height = BLOCK_HEIGHT;
// Очистить
initializeNewGame();
}
function rykaOnMouseOut(e) {
// Удаление
if (selectedBlock != null) {
imageBlockList[selectedBlock.no].isSelected = false;
selectedBlock = null;
DrawGame();
}
}
function rykaOnMouseDown(e) {
// Удаление
if (selectedBlock != null) {
imageBlockList[selectedBlock.no].isSelected = false;
}
selectedBlock = GetImageBlock(imageBlockList, e.pageX, e.pageY);
if (selectedBlock) {
imageBlockList[selectedBlock.no].isSelected = true;
}
}
function rykaOnMouseUp(e) {
if (selectedBlock) {
var index = selectedBlock.no;
// alert(index);
var block = GetImageBlock(blockList, e.pageX, e.pageY);
if (block) {
var blockOldImage = GetImageBlockOnEqual(imageBlockList, block.x, block.y);
if (blockOldImage == null) {
imageBlockList[index].x = block.x;
imageBlockList[index].y = block.y;
}
}
else {
imageBlockList[index].x = selectedBlock.x;
imageBlockList[index].y = selectedBlock.y;
}
imageBlockList[index].isSelected = false;
selectedBlock = null;
DrawGame();
if (isFinished()) {
OnFinished();
}
}
}
function rykaOnMouseMove(e) {
if (selectedBlock) {
selectedBlock.x = e.pageX - 25;
selectedBlock.y = e.pageY - 25;
DrawGame();
}
}
function clear(c) {
c.clearRect(0, 0, canvas.width, canvas.height);
}
function randomXtoY(minVal, maxVal, floatVal) {
var randVal = minVal + (Math.random() * (maxVal - minVal));
var val = typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
return Math.round(val);
}
function GetImageBlock(list, x, y) {
//for (var i = 0; i < list.length; i++) {
for (var i = list.length - 1; i >= 0; i--) {
var imgBlock = list[i];
var x1 = imgBlock.x;
var x2 = x1 + BLOCK_WIDTH;
var y1 = imgBlock.y;
var y2 = y1 + BLOCK_HEIGHT;
if (
(x >= x1 && x <= x2) &&
(y >= y1 && y <= y2)
) {
//alert("found: " + imgBlock.no);
var img = new imageBlock(imgBlock.no, imgBlock.x, imgBlock.y);
//drawImageBlock(img);
return img;
}
}
return null;
}
function GetImageBlockOnEqual(list, x, y) {
for (var i = 0; i < list.length; i++) {
var imgBlock = list[i];
var x1 = imgBlock.x;
var y1 = imgBlock.y;
if (
(x == x1) &&
(y == y1)
) {
var img = new imageBlock(imgBlock.no, imgBlock.x, imgBlock.y);
//drawImageBlock(img);
return img;
}
}
return null;
}
function isFinished() {
var total = TOTAL_PIECES;
for (var i = 0; i < total; i++) {
var img = imageBlockList[i];
var block = blockList[i];
if (
(img.x != block.x) ||
(img.y != block.y)
) {
return false;
}
}
return true;
}
}
|
получить ширину и высоту и разделить их на 2. это и будет центр
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
img{
position: absolute;
}
</style>
<body>
<img src="https://javascript.ru/forum/images/ca_serenity/misc/logo.gif" alt="">
<script>
var el = document.querySelector('img');
el.onmousedown = function(e) {
var a = [e.pageX - el.getBoundingClientRect().left, e.pageY - el.getBoundingClientRect().top];
document.onmousemove = e => el.style.cssText = 'left:'+(e.pageX-a[0])+'px; top:'+(e.pageY-a[1])+'px';
el.onmouseup = function() {
document.onmousemove = null;
el.onmouseup = null;
};
};
el.ondragstart = e => false;
</script>
</body>
</html>
|
Цитата:
Вот поиграться и понять можно тут: https://yadi.sk/d/35Dg9Yeo3Ub6mZ |
var x = el.clientWidth/2; var y = el.clientHeight/2; вот ваш центр! |
Цитата:
|
Miracle5,
function rykaOnMouseMove(e) {
if (selectedBlock) {
selectedBlock.x = e.pageX+xx;
selectedBlock.y = e.pageY+yy;
DrawGame();
}
}
var xx = yy = 0;
function GetImageBlock(list, x, y) {
//for (var i = 0; i < list.length; i++) {
for (var i = list.length - 1; i >= 0; i--) {
var imgBlock = list[i];
var x1 = imgBlock.x;
var x2 = x1 + BLOCK_WIDTH;
var y1 = imgBlock.y;
var y2 = y1 + BLOCK_HEIGHT;
if (
(x >= x1 && x <= x2) &&
(y >= y1 && y <= y2)
) {
//alert("found: " + imgBlock.no);
xx = imgBlock.x - x;
yy = imgBlock.y - y
var img = new imageBlock(imgBlock.no, imgBlock.x, imgBlock.y);
//drawImageBlock(img);
return img;
}
}
return null;
}
|
| Часовой пояс GMT +3, время: 16:27. |