<script>
// Получение элементов DOM
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const colorButtons = document.querySelectorAll('.color-button');
const colorPicker = document.getElementById('colorPicker');
const lineWidthRange = document.getElementById('lineWidth');
const clearBtn = document.getElementById('clearBtn');
const saveBtn = document.getElementById('saveBtn');
const eraserBtn = document.getElementById('eraserBtn');
const penBtn = document.getElementById('penBtn');
const lineBtn = document.getElementById('lineBtn');
const rectangleBtn = document.getElementById('rectangleBtn');
const circleBtn = document.getElementById('circleBtn');
const triangleBtn = document.getElementById('triangleBtn');
const undoBtn = document.getElementById('undoBtn');
const redoBtn = document.getElementById('redoBtn');
const bringToFrontBtn = document.getElementById('bringToFrontBtn');
const sendToBackBtn = document.getElementById('sendToBackBtn');
// Переменные состояния
let isDrawing = false;
let isDragging = false;
let isResizing = false;
let currentColor = '#000000';
let lineWidth = 2;
let currentTool = 'pen'; // Возможные значения: pen, eraser, line, rectangle, circle, triangle
let shapes = []; // Массив для хранения фигур
let undoStack = [];
let redoStack = [];
let selectedShape = null;
let dragOffsetX = 0;
let dragOffsetY = 0;
let startX = 0;
let startY = 0;
const resizeHandleSize = 8;
// Класс для фигур
class Shape {
constructor(type, x, y, w, h, color, lineWidth, points=[]) {
this.type = type; // pen, eraser, line, rectangle, circle, triangle
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
this.lineWidth = lineWidth;
this.points = points; // Для freehand (pen)
}
draw(ctx) {
ctx.strokeStyle = this.color;
ctx.lineWidth = this.lineWidth;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.beginPath();
if (this.type === 'line') {
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.w, this.h);
} else if (this.type === 'rectangle') {
ctx.rect(this.x, this.y, this.w - this.x, this.h - this.y);
} else if (this.type === 'circle') {
const radius = Math.sqrt(Math.pow(this.w - this.x, 2) + Math.pow(this.h - this.y, 2));
ctx.arc(this.x, this.y, radius, 0, Math.PI * 2);
} else if (this.type === 'triangle') {
ctx.moveTo(this.x, this.y);
ctx.lineTo(this.w, this.h);
ctx.lineTo(2 * this.x - this.w, this.h);
ctx.closePath();
} else if (this.type === 'pen' || this.type === 'eraser') {
if (this.points.length < 2) return;
ctx.moveTo(this.points[0].x, this.points[0].y);
for (let i = 1; i < this.points.length; i++) {
ctx.lineTo(this.points[i].x, this.points[i].y);
}
}
ctx.stroke();
}
isPointInside(x, y) {
if (['pen', 'eraser'].includes(this.type)) {
// Для freehand рисунков можно реализовать детекцию, если необходимо
// Сейчас не реализовано
return false;
}
if (this.type === 'line') {
const distance = pointToLineDistance(x, y, this.x, this.y, this.w, this.h);
return distance <= this.lineWidth + 5;
} else if (this.type === 'rectangle') {
const width = this.w - this.x;
const height = this.h - this.y;
return x >= this.x && x <= this.x + width &&
y >= this.y && y <= this.y + height;
} else if (this.type === 'circle') {
const distance = Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2));
const radius = Math.sqrt(Math.pow(this.w - this.x, 2) + Math.pow(this.h - this.y, 2));
return distance <= radius + this.lineWidth;
} else if (this.type === 'triangle') {
// Barycentric Technique
const x1 = this.x, y1 = this.y;
const x2 = this.w, y2 = this.h;
const x3 = 2 * this.x - this.w, y3 = this.h;
const areaOrig = Math.abs((x1*(y2 - y3) + x2*(y3 - y1) + x3*(y1 - y2)) / 2.0);
const area1 = Math.abs((x - x1)*(y2 - y1) - (x2 - x1)*(y - y1)) / 2.0;
const area2 = Math.abs((x - x2)*(y3 - y2) - (x3 - x2)*(y - y2)) / 2.0;
const area3 = Math.abs((x - x3)*(y1 - y3) - (x1 - x3)*(y - y3)) / 2.0;
return (area1 + area2 + area3) <= (areaOrig + this.lineWidth);
}
return false;
}
getResizeHandle() {
return {
x: this.w,
y: this.h,
size: resizeHandleSize
};
}
isOverResizeHandle(x, y) {
const handle = this.getResizeHandle();
return x >= handle.x - handle.size && x <= handle.x + handle.size &&
y >= handle.y - handle.size && y <= handle.y + handle.size;
}
}
// Функция для расчёта расстояния от точки до линии
function pointToLineDistance(px, py, x1, y1, x2, y2) {
const A = px - x1;
const B = py - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const len_sq = C * C + D * D;
let param = -1;
if (len_sq !== 0) // in case of 0 length line
param = dot / len_sq;
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = px - xx;
const dy = py - yy;
return Math.sqrt(dx * dx + dy * dy);
}
// Перерисовка всех фигур
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
shapes.forEach(shape => shape.draw(ctx));
// Если есть выбранная фигура, выделить её
if (selectedShape) {
highlightShape(selectedShape);
}
}
// Выделение выбранной фигуры
function highlightShape(shape) {
ctx.save();
ctx.strokeStyle = 'blue';
ctx.lineWidth = 1;
ctx.setLineDash([5, 3]);
if (shape.type === 'line') {
ctx.beginPath();
ctx.moveTo(shape.x, shape.y);
ctx.lineTo(shape.w, shape.h);
ctx.stroke();
} else if (shape.type === 'rectangle') {
ctx.strokeRect(shape.x, shape.y, shape.w - shape.x, shape.h - shape.y);
} else if (shape.type === 'circle') {
const radius = Math.sqrt(Math.pow(shape.w - shape.x, 2) + Math.pow(shape.h - shape.y, 2));
ctx.beginPath();
ctx.arc(shape.x, shape.y, radius, 0, Math.PI * 2);
ctx.stroke();
} else if (shape.type === 'triangle') {
ctx.beginPath();
ctx.moveTo(shape.x, shape.y);
ctx.lineTo(shape.w, shape.h);
ctx.lineTo(2 * shape.x - shape.w, shape.h);
ctx.closePath();
ctx.stroke();
}
// Рисуем ресайз-хэндл
const handle = shape.getResizeHandle();
ctx.fillStyle = 'white';
ctx.strokeStyle = 'black';
ctx.setLineDash([]);
ctx.beginPath();
ctx.rect(handle.x - resizeHandleSize, handle.y - resizeHandleSize, resizeHandleSize * 2, resizeHandleSize * 2);
ctx.fill();
ctx.stroke();
ctx.restore();
}
// Отмена действия
function undo() {
if (undoStack.length > 0) {
redoStack.push(JSON.stringify(shapes));
const previousState = undoStack.pop();
shapes = JSON.parse(previousState, reviveShape);
selectedShape = null;
redraw();
}
}
// Повтор действия
function redo() {
if (redoStack.length > 0) {
undoStack.push(JSON.stringify(shapes));
const nextState = redoStack.pop();
shapes = JSON.parse(nextState, reviveShape);
selectedShape = null;
redraw();
}
}
// Функция для восстановления экземпляров Shape после JSON.parse
function reviveShape(key, value) {
if (value && value.type) {
const shape = new Shape(value.type, value.x, value.y, value.w, value.h, value.color, value.lineWidth, value.points);
return shape;
}
return value;
}
// Добавление фигур и элементов в undo stack
function pushToUndo() {
undoStack.push(JSON.stringify(shapes));
// Ограничение размера undo stack
if (undoStack.length > 50) {
undoStack.shift();
}
// Очистка redo stack
redoStack = [];
}
// Установка активного инструмента
function setActiveTool(toolButton, toolType) {
document.querySelectorAll('.tool-button').forEach(btn => btn.classList.remove('active'));
if (toolButton) {
toolButton.classList.add('active');
}
currentTool = toolType;
// Если выбран инструмент рисования, снять выделение с фигур
if (['pen', 'eraser', 'line', 'rectangle', 'circle', 'triangle'].includes(toolType)) {
selectedShape = null;
}
redraw();
}
// Инициализация: установка цветового пикера и толщины линии
colorPicker.value = '#000000';
// Установка текущего цвета и обновление активной кнопки цвета
colorButtons.forEach(button => {
button.addEventListener('click', () => {
currentColor = button.getAttribute('data-color');
colorPicker.value = currentColor;
// Снять активность инструментов
document.querySelectorAll('.tool-button').forEach(btn => btn.classList.remove('active'));
currentTool = 'pen';
});
});
// Изменение текущего цвета при выборе из цветового пикера
colorPicker.addEventListener('change', (e) => {
currentColor = e.target.value;
// Снять активность инструментов
document.querySelectorAll('.tool-button').forEach(btn => btn.classList.remove('active'));
currentTool = 'pen';
});
// Обновление толщины линии
lineWidthRange.addEventListener('input', (e) => {
lineWidth = e.target.value;
});
// Очистка холста
clearBtn.addEventListener('click', () => {
if (confirm('Вы действительно хотите очистить холст?')) {
pushToUndo();
shapes = [];
selectedShape = null;
redraw();
}
});
// Сохранение рисунка
saveBtn.addEventListener('click', () => {
const link = document.createElement('a');
link.download = 'рисунок.png';
link.href = canvas.toDataURL();
link.click();
});
// Undo и Redo
undoBtn.addEventListener('click', () => {
undo();
});
redoBtn.addEventListener('click', () => {
redo();
});
// Управление порядком наложения
bringToFrontBtn.addEventListener('click', () => {
if (selectedShape) {
const index = shapes.indexOf(selectedShape);
if (index > -1) {
pushToUndo();
shapes.splice(index, 1);
shapes.push(selectedShape);
redraw();
}
}
});
sendToBackBtn.addEventListener('click', () => {
if (selectedShape) {
const index = shapes.indexOf(selectedShape);
if (index > -1) {
pushToUndo();
shapes.splice(index, 1);
shapes.unshift(selectedShape);
redraw();
}
}
});
// Инструмент "Ластик"
eraserBtn.addEventListener('click', () => {
setActiveTool(eraserBtn, 'eraser');
});
// Инструмент "Перо"
penBtn.addEventListener('click', () => {
setActiveTool(penBtn, 'pen');
});
// Инструменты фигур
lineBtn.addEventListener('click', () => {
setActiveTool(lineBtn, 'line');
});
rectangleBtn.addEventListener('click', () => {
setActiveTool(rectangleBtn, 'rectangle');
});
circleBtn.addEventListener('click', () => {
setActiveTool(circleBtn, 'circle');
});
triangleBtn.addEventListener('click', () => {
setActiveTool(triangleBtn, 'triangle');
});
// Начало взаимодействия
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', endDrawing);
canvas.addEventListener('mouseout', endDrawing);
// Обработка сенсорных устройств
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', endDrawing);
function getMousePos(e) {
const rect = canvas.getBoundingClientRect();
if (e.touches) {
return {
x: e.touches[0].clientX - rect.left,
y: e.touches[0].clientY - rect.top
};
} else {
return {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
}
}
function startDrawing(e) {
e.preventDefault();
const pos = getMousePos(e);
startX = pos.x;
startY = pos.y;
// Проверка на выбор фигуры
const shape = getShapeAt(pos.x, pos.y);
if (shape) {
selectedShape = shape;
const handle = shape.getResizeHandle();
if (shape.isOverResizeHandle(pos.x, pos.y)) {
isResizing = true;
} else {
isDragging = true;
dragOffsetX = pos.x - shape.x;
dragOffsetY = pos.y - shape.y;
}
redraw();
return;
}
// Если не выбрана фигура, начинается новое рисование
isDrawing = true;
pushToUndo();
if (currentTool === 'pen' || currentTool === 'eraser') {
const color = currentTool === 'eraser' ? '#ffffff' : currentColor;
shapes.push(new Shape(currentTool, pos.x, pos.y, pos.x, pos.y, color, lineWidth, [{x: pos.x, y: pos.y}]));
} else if (['line', 'rectangle', 'circle', 'triangle'].includes(currentTool)) {
shapes.push(new Shape(currentTool, pos.x, pos.y, pos.x, pos.y, currentColor, lineWidth));
}
selectedShape = null;
redraw();
}
function draw(e) {
e.preventDefault();
const pos = getMousePos(e);
if (isDrawing) {
const currentShape = shapes[shapes.length - 1];
if (currentTool === 'pen' || currentTool === 'eraser') {
currentShape.points.push({x: pos.x, y: pos.y});
} else if (['line', 'rectangle', 'circle', 'triangle'].includes(currentTool)) {
currentShape.w = pos.x;
currentShape.h = pos.y;
}
redraw();
} else if (isDragging && selectedShape) {
selectedShape.x = pos.x - dragOffsetX;
selectedShape.y = pos.y - dragOffsetY;
// Для фигур, кроме пера и ластика, обновляем координаты
if (['line', 'rectangle', 'circle', 'triangle'].includes(selectedShape.type)) {
selectedShape.w = selectedShape.type === 'line' ? selectedShape.w + (pos.x - startX) : selectedShape.w;
selectedShape.h = selectedShape.type === 'line' ? selectedShape.h + (pos.y - startY) : selectedShape.h;
}
redraw();
} else if (isResizing && selectedShape) {
selectedShape.w = pos.x;
selectedShape.h = pos.y;
redraw();
}
}
function endDrawing(e) {
if (isDrawing || isDragging || isResizing) {
pushToUndo();
}
isDrawing = false;
isDragging = false;
isResizing = false;
}
// Обработка клавиатурных сокращений для Undo и Redo
document.addEventListener('keydown', (e) => {
if (e.ctrlKey && e.key === 'z') {
undo();
}
if (e.ctrlKey && e.key === 'y') {
redo();
}
});
// Получение фигуры под курсором
function getShapeAt(x, y) {
for (let i = shapes.length - 1; i >= 0; i--) {
if (shapes[i].isPointInside(x, y)) {
return shapes[i];
}
}
return null;
}
// Функция для преобразования RGB в HEX (если необходимо)
function rgbToHex(color) {
// Создаём временный элемент для получения computed стиля
const tempElem = document.createElement('div');
tempElem.style.color = color;
document.body.appendChild(tempElem);
const rgb = getComputedStyle(tempElem).color;
document.body.removeChild(tempElem);
const result = rgb.match(/\d+/g).map(Number);
return "#" + ((1 << 24) + (result[0] << 16) + (result[1] << 8) + result[2]).toString(16).slice(1);
}
// Перерисовка по умолчанию (можно добавить фон или другие элементы)
redraw();
</script>
Конечно, я помогу вам исправить ваш код. Судя по представленному коду, у вас есть приложение для рисования с возможностью Undo/Redo и манипуляции фигурами. Я предполагаю, что у вас возникают проблемы с перетаскиванием и изменением размера фигур.
Основная проблема заключается в том, что при перетаскивании фигур обновляются только x и y, но не обновляются w и h (координаты конца фигуры). Это приводит к тому, что фигуры не перемещаются корректно. Давайте исправим это.
Вот исправленный код с комментариями по внесенным изменениям:
html
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Улучшенная Рисовалка с Undo/Redo и Манипуляцией Фигурами</title>
<!-- Подключение Google Fonts для улучшения типографики -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<style>
/* Ваш CSS остается без изменений */
</style>
</head>
<body>
<!-- Ваш HTML остается без изменений -->
<h1>Улучшенная Рисовалка с Undo/Redo и Манипуляцией Фигурами</h1>
<div id="toolbar">
<!-- ... остальной HTML для панели инструментов ... -->
</div>
<div id="canvasContainer">
<canvas id="canvas" width="1200" height="700"></canvas>
</div>
<script>
// Ваш JavaScript код
// ... предыдущие переменные и классы остаются без изменений ...
// Функция для перерисовки всех фигур
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
shapes.forEach(shape => shape.draw(ctx));
// Если есть выбранная фигура, выделить её
if (selectedShape) {
highlightShape(selectedShape);
}
}
// Обновленная функция начала взаимодействия
function startDrawing(e) {
e.preventDefault();
const pos = getMousePos(e);
startX = pos.x;
startY = pos.y;
// Проверка на выбор фигуры
const shape = getShapeAt(pos.x, pos.y);
if (shape) {
selectedShape = shape;
const handle = shape.getResizeHandle();
if (shape.isOverResizeHandle(pos.x, pos.y)) {
isResizing = true;
// Сохранение начальных координат для резайза
resizeStartX = pos.x;
resizeStartY = pos.y;
originalWidth = shape.w;
originalHeight = shape.h;
} else {
isDragging = true;
dragOffsetX = pos.x - shape.x;
dragOffsetY = pos.y - shape.y;
}
redraw();
return;
}
// Если не выбрана фигура, начинается новое рисование
isDrawing = true;
pushToUndo();
if (currentTool === 'pen' || currentTool === 'eraser') {
const color = currentTool === 'eraser' ? '#ffffff' : currentColor;
shapes.push(new Shape(currentTool, pos.x, pos.y, pos.x, pos.y, color, lineWidth, [{x: pos.x, y: pos.y}]));
} else if (['line', 'rectangle', 'circle', 'triangle'].includes(currentTool)) {
shapes.push(new Shape(currentTool, pos.x, pos.y, pos.x, pos.y, currentColor, lineWidth));
}
selectedShape = null;
redraw();
}
// Обновленная функция рисования
function draw(e) {
e.preventDefault();
const pos = getMousePos(e);
if (isDrawing) {
const currentShape = shapes[shapes.length - 1];
if (currentTool === 'pen' || currentTool === 'eraser') {
currentShape.points.push({x: pos.x, y: pos.y});
} else if (['line', 'rectangle', 'circle', 'triangle'].includes(currentTool)) {
currentShape.w = pos.x;
currentShape.h = pos.y;
}
redraw();
} else if (isDragging && selectedShape) {
const dx = pos.x - startX;
const dy = pos.y - startY;
selectedShape.x += dx;
selectedShape.y += dy;
// Обновляем конечные координаты фигуры
if (['line', 'rectangle', 'circle', 'triangle'].includes(selectedShape.type)) {
selectedShape.w += dx;
selectedShape.h += dy;
} else if (selectedShape.type === 'pen' || selectedShape.type === 'eraser') {
// Смещаем все точки для инструментов "Перо" и "Ластик"
selectedShape.points.forEach(point => {
point.x += dx;
point.y += dy;
});
}
startX = pos.x;
startY = pos.y;
redraw();
} else if (isResizing && selectedShape) {
// Вычисляем изменение размеров
const dx = pos.x - resizeStartX;
const dy = pos.y - resizeStartY;
if (selectedShape.type === 'rectangle' || selectedShape.type === 'line' || selectedShape.type === 'circle' || selectedShape.type === 'triangle') {
selectedShape.w = originalWidth + dx;
selectedShape.h = originalHeight + dy;
}
redraw();
}
}
// Обновленная функция окончания взаимодействия
function endDrawing(e) {
if (isDrawing || isDragging || isResizing) {
pushToUndo();
}
isDrawing = false;
isDragging = false;
isResizing = false;
selectedShape = null;
}
// Обновление функции isPointInside для инструмента "Перо" и "Ластик"
Shape.prototype.isPointInside = function(x, y) {
if (this.type === 'pen' || this.type === 'eraser') {
// Для инструмента "Перо" проверяем, находится ли точка рядом с какой-либо точкой линии
return this.points.some(point => {
const dx = x - point.x;
const dy = y - point.y;
return Math.sqrt(dx * dx + dy * dy) <= this.lineWidth + 5;
});
}
// Оставляем остальные проверки без изменений
// ...
};
// Добавьте недостающие переменные
let resizeStartX = 0;
let resizeStartY = 0;
let originalWidth = 0;
let originalHeight = 0;
// Остальной код остается без изменений
// ...
// Перерисовка по умолчанию
redraw();
</script>
</body>
</html>
Объяснение внесенных изменений:
Перетаскивание фигур:
В функции draw при перетаскивании (isDragging) теперь мы обновляем не только selectedShape.x и selectedShape.y, но и selectedShape.w и selectedShape.h для соответствующих фигур. Это позволяет корректно перемещать фигуры по холсту.
Для инструментов "Перо" и "Ластик" мы также смещаем все точки points, чтобы линия перемещалась вместе с фигурой.
Изменение размера фигур:
Добавлены переменные resizeStartX, resizeStartY, originalWidth, originalHeight для отслеживания начальных значений при изменении размера.
В функции startDrawing, при начале изменения размера (isResizing), мы сохраняем эти значения.
В функции draw, при изменении размера, мы вычисляем смещение и обновляем размеры фигуры соответственно.
Выбор и перемещение инструментов "Перо" и "Ластик":
Обновлена функция isPointInside для класса Shape, чтобы она могла определять, находится ли точка внутри линии, созданной инструментами "Перо" или "Ластик".
При перетаскивании этих фигур мы перемещаем каждую точку, чтобы линия оставалась цельной.
Обнуление selectedShape в конце взаимодействия:
В функции endDrawing добавлено selectedShape = null;, чтобы снять выделение с фигуры после завершения взаимодействия.
Исправление логики Undo/Redo:
Убедитесь, что pushToUndo() вызывается только при начале рисования или при окончании перетаскивания/изменения размера, чтобы не создавать лишних записей в стеке действий.
Примечание: Убедитесь, что все переменные объявлены и не вызывают ошибок. После внесения этих изменений ваше приложение должно корректно обрабатывать перемещение и изменение размера фигур, а также правильно работать с инструментами "Перо" и "Ластик".
Если у вас возникнут дополнительные вопросы или потребуется дальнейшая помощь, пожалуйста, дайте мне знать!