/
Gabryelf
/
Pixel-Orb
Обзор
Документация
Войти
/
Gabryelf
/
Pixel-Orb
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/client/tools/LineTool.js
88 строк
3 KB
Valeev Serj
restruct_v0.0.1
07 авг 2026, 22:50
07 авг 2026, 22:50
41f78a4
Код
Авторство
О чём код?
import Tool from './Tool.js'; class LineTool extends Tool { constructor(canvas, context) { super(canvas, context); this.name = 'line'; this.icon = '📏'; this.description = 'Draw straight lines'; this.startX = 0; this.startY = 0; this.tempCanvas = null; this.tempContext = null; } onMouseDown(x, y) { this.isDrawing = true; this.startX = x; this.startY = y; this.lastX = x; this.lastY = y; // Создаем временный холст для предпросмотра this.tempCanvas = document.createElement('canvas'); this.tempCanvas.width = this.canvas.width; this.tempCanvas.height = this.canvas.height; this.tempContext = this.tempCanvas.getContext('2d'); } onMouseMove(x, y) { if (this.isDrawing) { // Очищаем временный холст this.tempContext.clearRect(0, 0, this.tempCanvas.width, this.tempCanvas.height); // Копируем основной холст this.tempContext.drawImage(this.canvas, 0, 0); // Рисуем линию на временном холсте this.drawLineOnContext(this.tempContext, this.startX, this.startY, x, y); // Отображаем временный холст this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); this.context.drawImage(this.tempCanvas, 0, 0); } } onMouseUp(x, y) { if (this.isDrawing) { // Рисуем финальную линию на основном холсте this.drawLine(this.startX, this.startY, x, y); this.isDrawing = false; // Удаляем временный холст this.tempCanvas = null; this.tempContext = null; } } drawLineOnContext(ctx, x1, y1, x2, y2) { const pixelSize = this.getPixelSize(); const color = this.color; const size = this.size; ctx.fillStyle = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a / 255})`; const dx = Math.abs(x2 - x1); const dy = Math.abs(y2 - y1); const sx = x1 < x2 ? 1 : -1; const sy = y1 < y2 ? 1 : -1; let err = dx - dy; let cx = x1, cy = y1; while (true) { ctx.fillRect(cx * pixelSize, cy * pixelSize, pixelSize * size, pixelSize * size); if (cx === x2 && cy === y2) break; const e2 = 2 * err; if (e2 > -dy) { err -= dy; cx += sx; } if (e2 < dx) { err += dx; cy += sy; } } } } export default LineTool;