Certainly! Below is the complete HTML, CSS, and JavaScript code with the necessary fixes to ensure that SVG shapes can have gradients applied correctly. The gradient tool now applies gradients individually to selected elements, updates live with changes, and ensures only one element is selected at a time with a single selection outline and resize handles.
Key Changes Implemented:
-
Gradient Application to SVG Shapes:
- Each SVG shape now includes a
<defs> section to define gradients.
- When a gradient is applied, a unique gradient definition is created or updated within the
<defs>.
- The shape's
fill attribute is set to reference the defined gradient using url(#gradientId).
-
Individual Selection Handling:
- Only one element can be selected at a time.
- The selection outline (
canvasOutline) and resize handles are displayed for the currently selected element only.
- Multiple selections are prevented to ensure individual styling and gradient application.
-
Live Gradient Updates:
- Changes to gradient properties (type, angle, colors) immediately reflect on the selected shape.
- The gradient tool listens for input changes and updates the gradient in real-time.
-
Unique Gradient IDs:
- Each shape has a unique gradient ID based on its element ID to prevent conflicts.
- This ensures that gradients are applied and managed individually per element.
Below is the fully updated code with these enhancements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Enhanced Notion-like Canvas</title>
<!-- Include Material Icons for UI Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Include Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Source+Sans+Pro:wght@400;700&display=swap" rel="stylesheet">
<style>
/* General Styles */
body, html {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
font-family: 'Source Sans Pro', 'Roboto', sans-serif;
color: #37352f;
background-color: #f5f5f5;
}
.container {
display: flex;
height: 100%;
position: relative;
}
.toolbar {
width: 60px;
background-color: #fbfbfa;
border-right: 1px solid #e0e0e0;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 20px;
position: relative;
z-index: 2;
}
.tool-button {
width: 40px;
height: 40px;
border: none;
background-color: transparent;
cursor: pointer;
margin-bottom: 10px;
border-radius: 5px;
display: flex;
justify-content: center;
align-items: center;
transition: background-color 0.3s ease;
color: #37352f;
position: relative;
font-size: 24px;
}
.tool-button:hover {
background-color: #f1f1ef;
}
.tool-button i {
pointer-events: none;
}
.tool-button .tooltip {
visibility: hidden;
background-color: #37352f;
color: #fff;
text-align: center;
border-radius: 5px;
padding: 5px;
position: absolute;
left: 45px;
z-index: 1;
font-size: 12px;
white-space: nowrap;
}
.tool-button:hover .tooltip {
visibility: visible;
}
.tool-dropdown {
position: relative;
}
.shape-menu {
display: none;
position: absolute;
top: 50px;
left: 0;
background-color: #fbfbfa;
border: 1px solid #e0e0e0;
border-radius: 5px;
z-index: 1000;
padding: 5px;
flex-direction: column;
}
.shape-menu .tool-button {
margin: 5px;
}
.canvas-area {
flex: 1;
background-color: #f7f6f3;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
position: relative;
overflow: hidden;
}
.canvas-controls {
margin-bottom: 10px;
display: flex;
align-items: center;
position: relative;
z-index: 1;
gap: 10px;
}
.canvas-controls button,
.canvas-controls input[type="color"],
.canvas-controls input[type="range"] {
background-color: #e0e0e0;
color: #37352f;
border: none;
padding: 8px 12px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s ease;
display: flex;
align-items: center;
}
.canvas-controls button:hover,
.canvas-controls input[type="color"]:hover {
background-color: #d0d0d0;
}
.canvas-controls input[type="range"] {
width: 100px;
padding: 0;
margin: 0;
cursor: pointer;
background-color: transparent;
}
.canvas-container {
position: relative;
flex: 1;
width: 100%;
max-width: 1200px;
background-color: #fff;
border: 1px solid #e0e0e0;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
cursor: default;
overflow: hidden;
}
.canvas {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
background-color: #ffffff;
}
.grid {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: linear-gradient(to right, #f0f0f0 1px, transparent 1px),
linear-gradient(to bottom, #f0f0f0 1px, transparent 1px);
background-size: 20px 20px;
pointer-events: none;
display: none;
}
.chat-area {
width: 350px;
background-color: #fbfbfa;
border-left: 1px solid #e0e0e0;
display: flex;
flex-direction: column;
z-index: 1;
}
.chat-header {
padding: 16px;
font-size: 16px;
font-weight: 600;
border-bottom: 1px solid #e0e0e0;
background-color: #f7f6f3;
}
.chat-messages {
flex: 1;
overflow-y: auto;
padding: 16px;
}
.message {
margin-bottom: 12px;
padding: 8px 12px;
background-color: #f1f1ef;
border-radius: 8px;
font-size: 14px;
}
.chat-input {
border-top: 1px solid #e0e0e0;
padding: 16px;
background-color: #f7f6f3;
}
.chat-input form {
display: flex;
align-items: center;
}
.chat-input input {
flex: 1;
padding: 10px 12px;
border: 1px solid #e0e0e0;
border-radius: 5px;
font-size: 14px;
background-color: #ffffff;
}
.chat-input button {
margin-left: 8px;
padding: 10px 16px;
background-color: #e0e0e0;
color: #37352f;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s ease;
}
.chat-input button:hover {
background-color: #d0d0d0;
}
.canvas-text, .canvas-media, .canvas-shape {
position: absolute;
cursor: move;
user-select: none;
min-width: 50px;
min-height: 20px;
z-index: 1;
}
.canvas-text {
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
overflow: hidden;
}
.canvas-text div {
padding: 5px;
outline: none;
width: 100%;
height: 100%;
font-family: 'Roboto', sans-serif;
font-size: 16px;
color: #333;
text-align: left;
cursor: text;
}
.canvas-media img {
max-width: 100%;
max-height: 100%;
display: block;
}
.canvas-media {
padding: 0;
overflow: hidden;
}
/* Shape styles */
.canvas-shape {
overflow: visible; /* Allow stroke to be visible */
}
.canvas-shape svg {
overflow: visible; /* Ensure stroke is visible */
}
/* Gradient Tool */
.gradient-tool,
.gradient-stroke-tool {
position: absolute;
top: 60px;
left: 70px;
background-color: #ffffff;
border: 1px solid #e0e0e0;
border-radius: 5px;
padding: 10px;
display: none;
flex-direction: column;
gap: 10px;
z-index: 1000;
}
.gradient-option {
display: flex;
align-items: center;
gap: 5px;
}
.gradient-preview {
width: 30px;
height: 30px;
border: 1px solid #e0e0e0;
border-radius: 3px;
}
/* Resize Handles */
.resize-handle {
position: absolute;
width: 10px;
height: 10px;
background-color: #fff;
border: 1px solid #000;
z-index: 10;
cursor: pointer;
}
.resize-handle.top-left {
left: -5px;
top: -5px;
cursor: nwse-resize;
}
.resize-handle.top-right {
right: -5px;
top: -5px;
cursor: nesw-resize;
}
.resize-handle.bottom-left {
left: -5px;
bottom: -5px;
cursor: nesw-resize;
}
.resize-handle.bottom-right {
right: -5px;
bottom: -5px;
cursor: nwse-resize;
}
/* Layers Panel Styles */
.layer-panel {
position: absolute;
top: 0;
right: 0;
width: 250px;
height: 100%;
background-color: #fbfbfa;
color: #37352f;
border-left: 1px solid #e0e0e0;
display: flex;
flex-direction: column;
z-index: 1;
overflow: hidden;
}
.layer-panel-header {
padding: 10px;
font-size: 16px;
font-weight: bold;
border-bottom: 1px solid #e0e0e0;
background-color: #f7f6f3;
cursor: move;
}
.layer-list {
flex: 1;
overflow-y: auto;
padding: 10px;
}
.layer-list-item {
display: flex;
align-items: center;
padding: 5px;
margin-bottom: 5px;
border: 1px solid transparent;
cursor: pointer;
background-color: #fbfbfa;
border-radius: 3px;
}
.layer-list-item:hover {
background-color: #f1f1ef;
border-color: #e0e0e0;
}
.layer-thumbnail canvas {
width: 40px;
height: 40px;
background-color: #fff;
border: 1px solid #ccc;
}
.layer-name {
flex: 1;
margin-left: 10px;
font-size: 14px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.layer-controls {
display: flex;
align-items: center;
gap: 5px;
}
.layer-controls .material-icons {
cursor: pointer;
color: #999;
font-size: 20px;
}
.layer-controls .material-icons:hover {
color: #37352f;
}
/* Code Area */
.code-area {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 200px;
background-color: #1e1e1e;
color: #dcdcdc;
display: none;
overflow: auto;
padding: 10px;
font-family: 'Courier New', Courier, monospace;
font-size: 14px;
z-index: 1000;
resize: vertical;
border-top: 1px solid #444;
}
.code-area pre {
margin: 0;
}
/* Toggle Code Button */
.toggle-code {
position: absolute;
bottom: 10px;
right: 10px;
background-color: #e0e0e0;
border: none;
padding: 6px 10px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
color: #37352f;
transition: background-color 0.3s ease;
z-index: 2;
}
.toggle-code:hover {
background-color: #d0d0d0;
}
/* Font Controls Styling */
.text-controls input[type="number"],
.text-controls select {
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.text-controls button {
background-color: #f9f9f9;
border: 1px solid #ccc;
}
.text-controls button.active {
background-color: #e0e0e0;
}
.text-controls {
font-family: 'Source Sans Pro', sans-serif;
font-size: 13px;
}
/* Prevent toolboxes from overlapping gradient tools */
#text-controls-wrapper,
#media-controls-wrapper,
#shape-controls-wrapper {
position: absolute;
top: 0;
left: 0;
z-index: 1001;
}
/* Responsive Adjustment for Toolboxes */
@media (max-width: 1200px) {
.layer-panel {
width: 200px;
}
.chat-area {
width: 300px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="toolbar">
<button class="tool-button" onclick="addText()" title="Add Text">
<i class="material-icons">text_fields</i>
<span class="tooltip">Add Text</span>
</button>
<button class="tool-button" onclick="addMedia()" title="Add Media">
<i class="material-icons">image</i>
<span class="tooltip">Add Media</span>
</button>
<button class="tool-button" onclick="copyElements()" title="Copy">
<i class="material-icons">content_copy</i>
<span class="tooltip">Copy (Ctrl+C)</span>
</button>
<button class="tool-button" onclick="pasteElements()" title="Paste">
<i class="material-icons">content_paste</i>
<span class="tooltip">Paste (Ctrl+V)</span>
</button>
<div class="tool-dropdown">
<button class="tool-button shape-tool-button" onclick="toggleShapeMenu(event)" title="Add Shape">
<i class="material-icons">category</i>
<span class="tooltip">Add Shape</span>
</button>
<div class="shape-menu" id="shapeMenu">
<button class="tool-button" onclick="selectShape('rectangle')" title="Rectangle">
<i class="material-icons">crop_square</i>
</button>
<button class="tool-button" onclick="selectShape('ellipse')" title="Ellipse">
<i class="material-icons">circle</i>
</button>
<button class="tool-button" onclick="selectShape('star')" title="Star">
<i class="material-icons">star</i>
</button>
<button class="tool-button" onclick="selectShape('triangle')" title="Triangle">
<i class="material-icons">change_history</i>
</button>
<!-- New Shapes -->
<button class="tool-button" onclick="selectShape('pentagon')" title="Pentagon">
<i class="material-icons">pentagon</i>
</button>
<button class="tool-button" onclick="selectShape('hexagon')" title="Hexagon">
<i class="material-icons">hexagon</i>
</button>
<button class="tool-button" onclick="selectShape('octagon')" title="Octagon">
<i class="material-icons">stop</i>
</button>
</div>
</div>
<!-- Removed Gradient Stroke Tool for Normal Stroke -->
<button class="tool-button" onclick="toggleGradientTool()" title="Gradient Fill">
<i class="material-icons">gradient</i>
<span class="tooltip">Gradient Fill</span>
</button>
<!-- Added Normal Stroke Tool -->
<button class="tool-button" onclick="toggleStrokeTool()" title="Stroke">
<i class="material-icons">border_outer</i>
<span class="tooltip">Stroke</span>
</button>
<button class="tool-button" onclick="deleteElement()" title="Delete">
<i class="material-icons">delete</i>
<span class="tooltip">Delete (Delete)</span>
</button>
<button class="tool-button" onclick="undo()" title="Undo">
<i class="material-icons">undo</i>
<span class="tooltip">Undo (Ctrl+Z)</span>
</button>
<button class="tool-button" onclick="redo()" title="Redo">
<i class="material-icons">redo</i>
<span class="tooltip">Redo (Ctrl+Y)</span>
</button>
</div>
<div class="canvas-area">
<div class="canvas-controls">
<button class="toggle-grid" onclick="toggleGrid()" title="Toggle Grid">
<i class="material-icons">grid_on</i>
</button>
<input type="color" id="canvasColorPicker" oninput="changeCanvasColor(this.value)" title="Canvas Color">
<!-- Opacity Control -->
<input type="range" min="0" max="100" value="100" id="globalOpacity" oninput="changeGlobalOpacity(this.value)" title="Opacity">
<button class="toggle-code" onclick="toggleCode()" title="Toggle Code">
<i class="material-icons">code</i>
</button>
</div>
<div class="canvas-container" id="canvasContainer">
<div class="canvas" id="canvas">
<div class="grid" id="grid"></div>
</div>
<div class="canvas-outline" id="canvasOutline"></div>
</div>
<div class="gradient-tool" id="gradientTool">
<div class="gradient-option">
<span>Gradient Type:</span>
<select id="gradientType" onchange="updateGradientPreview(); updateSelectedShapeGradient();">
<option value="linear">Linear</option>
<option value="radial">Radial</option>
<option value="conic">Conic</option>
</select>
</div>
<div class="gradient-option">
<span>Angle:</span>
<input type="number" id="gradientAngle" value="90" onchange="updateGradientPreview(); updateSelectedShapeGradient();">°
</div>
<div class="gradient-option">
<span>Colors:</span>
<div id="gradientColors"></div>
<button onclick="addGradientColor()">Add Color</button>
</div>
<div class="gradient-option">
<span>Preview:</span>
<div class="gradient-preview" id="gradientPreview"></div>
</div>
</div>
<!-- Added Stroke Tool -->
<div class="gradient-stroke-tool" id="strokeTool" style="display: none;">
<div class="gradient-option">
<span>Stroke Color:</span>
<input type="color" id="strokeColor" onchange="updateSelectedStroke()" title="Stroke Color">
</div>
<div class="gradient-option">
<span>Stroke Width:</span>
<input type="number" id="strokeWidth" min="1" max="20" value="2" onchange="updateSelectedStroke()" title="Stroke Width">px
</div>
<div class="gradient-option">
<span>Continuous Stroke:</span>
<input type="checkbox" id="continuousStroke" onchange="updateSelectedStroke()" title="Continuous Stroke">
</div>
<div class="gradient-option">
<span>Preview:</span>
<div class="gradient-preview" id="strokePreview" style="background: #000;"></div>
</div>
</div>
<div class="layer-panel" id="layerPanel">
<div class="layer-panel-header" id="layerPanelHeader">Layers</div>
<ul class="layer-list" id="layerList"></ul>
</div>
</div>
<div class="code-area" id="codeArea">
<pre id="code"></pre>
</div>
<div class="chat-area">
<div class="chat-header">
Chat
</div>
<div class="chat-messages">
<div class="message">Hello! How can I help you with your design?</div>
<div class="message">You can use the canvas on the left to create your poster.</div>
</div>
<div class="chat-input">
<form onsubmit="sendMessage(event)">
<input type="text" placeholder="Type a message..." required>
<button type="submit">Send</button>
</form>
</div>
</div>
<div id="text-controls-wrapper"></div>
<div id="media-controls-wrapper"></div>
<div id="shape-controls-wrapper"></div>
</div>
<script>
let currentShape = null;
let copiedElement = null;
let codeArea = document.getElementById('codeArea');
let codeElement = document.getElementById('code');
let gradientTool = document.getElementById('gradientTool');
let strokeTool = document.getElementById('strokeTool'); // Renamed for clarity
let undoStack = [];
let redoStack = [];
let gradientColors = ['#ff0000', '#0000ff'];
let isGradientToolActive = false;
let isStrokeToolActive = false;
const svgNS = "http://www.w3.org/2000/svg";
function toggleGrid() {
const grid = document.getElementById('grid');
grid.style.display = grid.style.display === 'none' ? 'block' : 'none';
saveState();
}
function changeCanvasColor(color) {
const canvas = document.getElementById('canvas');
canvas.style.backgroundColor = color;
updateCode(); // Update code when background color changes
saveState();
}
function addText() {
const canvas = document.getElementById('canvas');
const text = document.createElement('div');
text.className = 'canvas-text';
text.id = 'text-' + Date.now();
const textContent = document.createElement('div');
textContent.contentEditable = true;
textContent.textContent = 'Double click to edit';
textContent.setAttribute('tabindex', '0'); // Make it focusable
text.appendChild(textContent);
text.style.left = '50px';
text.style.top = '50px';
text.style.width = '200px';
text.style.height = '50px';
textContent.style.fontSize = '16px';
textContent.style.color = '#000000';
text.style.opacity = 1;
canvas.appendChild(text);
makeDraggable(text);
makeSelectable(text);
addTextControls(text);
text.addEventListener('dblclick', function() {
textContent.focus();
document.execCommand('selectAll', false, null);
});
textContent.addEventListener('input', function() {
updateLayerPanel();
updateCode();
saveState();
});
updateLayerPanel();
updateCode();
saveState();
}
function addMedia() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.onchange = function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const canvas = document.getElementById('canvas');
const media = document.createElement('div');
media.className = 'canvas-media';
media.id = 'media-' + Date.now();
const img = document.createElement('img');
img.src = e.target.result;
img.dataset.scale = 1;
img.style.transformOrigin = 'center center';
img.onwheel = (e) => {
e.preventDefault();
zoomMedia(img, e);
};
img.ondragstart = () => false;
media.appendChild(img);
img.onload = function() {
let scale = 1;
if (img.naturalWidth > 400 || img.naturalHeight > 300) {
// Scale down if image is too big
scale = Math.min(400 / img.naturalWidth, 300 / img.naturalHeight);
}
media.style.width = img.naturalWidth * scale + 'px';
media.style.height = img.naturalHeight * scale + 'px';
media.style.left = '50px';
media.style.top = '50px';
media.style.opacity = 1;
img.style.width = '100%';
img.style.height = '100%';
};
canvas.appendChild(media);
makeDraggable(media);
makeSelectable(media);
addMediaControls(media);
updateLayerPanel();
updateCode();
saveState();
};
reader.readAsDataURL(file);
}
};
input.click();
}
function toggleShapeMenu(event) {
event.stopPropagation(); // Prevent event from bubbling up
const menu = document.getElementById('shapeMenu');
menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
}
document.addEventListener('click', function(e) {
const menu = document.getElementById('shapeMenu');
const button = document.querySelector('.tool-dropdown .tool-button');
if (menu.style.display === 'block' && !menu.contains(e.target) && !button.contains(e.target)) {
menu.style.display = 'none';
}
});
function selectShape(shapeType) {
currentShape = shapeType;
const menu = document.getElementById('shapeMenu');
menu.style.display = 'none';
}
document.getElementById('canvas').addEventListener('click', function(event) {
if (currentShape) {
const canvas = document.getElementById('canvas');
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
addShape(currentShape, x, y);
currentShape = null;
updateCode();
saveState();
} else {
clearSelection();
}
});
function addShape(shapeType, x, y) {
const canvas = document.getElementById('canvas');
const shapeWrapper = document.createElement('div');
shapeWrapper.className = 'canvas-shape';
shapeWrapper.id = `${shapeType}-${Date.now()}`;
shapeWrapper.style.left = `${x}px`;
shapeWrapper.style.top = `${y}px`;
shapeWrapper.style.opacity = 1;
shapeWrapper.dataset.shapeType = shapeType;
const svg = document.createElementNS(svgNS, 'svg');
svg.setAttribute('width', '100');
svg.setAttribute('height', '100');
svg.setAttribute('viewBox', '0 0 100 100');
svg.style.overflow = 'visible';
// Add defs for gradients
const defs = document.createElementNS(svgNS, 'defs');
svg.appendChild(defs);
let shape;
if (shapeType === 'rectangle') {
shape = document.createElementNS(svgNS, 'rect');
shape.setAttribute('x', 0);
shape.setAttribute('y', 0);
shape.setAttribute('width', 100);
shape.setAttribute('height', 100);
shape.style.fill = '#3498db';
} else if (shapeType === 'ellipse') {
shape = document.createElementNS(svgNS, 'ellipse');
shape.setAttribute('cx', 50);
shape.setAttribute('cy', 50);
shape.setAttribute('rx', 50);
shape.setAttribute('ry', 50);
shape.style.fill = '#e74c3c';
} else if (shapeType === 'triangle') {
shape = document.createElementNS(svgNS, 'polygon');
shape.setAttribute('points', '50,0 0,100 100,100');
shape.style.fill = '#2ecc71';
} else if (shapeType === 'star') {
shape = document.createElementNS(svgNS, 'polygon');
shape.setAttribute('points', '50,0 61,35 98,35 68,57 79,91 50,70 21,91 32,57 2,35 39,35');
shape.style.fill = '#f1c40f';
} else if (shapeType === 'pentagon') {
shape = document.createElementNS(svgNS, 'polygon');
shape.setAttribute('points', '50,0 95,35 75,90 25,90 5,35');
shape.style.fill = '#8e44ad';
} else if (shapeType === 'hexagon') {
shape = document.createElementNS(svgNS, 'polygon');
shape.setAttribute('points', '25,0 75,0 100,50 75,100 25,100 0,50');
shape.style.fill = '#e67e22';
} else if (shapeType === 'octagon') {
shape = document.createElementNS(svgNS, 'polygon');
shape.setAttribute('points', '30,0 70,0 100,30 100,70 70,100 30,100 0,70 0,30');
shape.style.fill = '#2c3e50';
}
svg.appendChild(shape);
shapeWrapper.appendChild(svg);
// Set default stroke properties
shape.setAttribute('stroke', '#000000');
shape.setAttribute('stroke-width', '2');
shape.setAttribute('stroke-dasharray', ''); // For solid stroke
// Assign a unique gradient ID for the shape
const gradientId = `${shapeWrapper.id}-gradient`;
shapeWrapper.dataset.gradientId = gradientId;
canvas.appendChild(shapeWrapper);
makeDraggable(shapeWrapper);
makeSelectable(shapeWrapper);
addShapeControls(shapeWrapper, shapeType);
updateLayerPanel();
updateCode();
saveState();
}
function makeDraggable(element) {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
const canvas = document.getElementById('canvas');
let isResizing = false;
let currentHandle = null;
if (element.classList.contains('canvas-text') || element.classList.contains('canvas-media') || element.classList.contains('canvas-shape')) {
addResizeHandles(element);
}
element.onmousedown = dragMouseDown;
function dragMouseDown(e) {
if (element.dataset.locked === 'true') {
return;
}
if (e.target.classList.contains('resize-handle')) {
isResizing = true;
currentHandle = e.target;
e.stopPropagation();
document.onmouseup = closeDragElement;
document.onmousemove = elementResize;
} else {
e = e || window.event;
e.preventDefault();
e.stopPropagation();
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
clearSelection();
element.classList.add('selected');
showElementControls(element);
}
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
let newTop = element.offsetTop - pos2;
let newLeft = element.offsetLeft - pos1;
// Constraints so that the element does not leave the canvas
let maxTop = canvas.offsetHeight - element.offsetHeight;
let maxLeft = canvas.offsetWidth - element.offsetWidth;
if (newTop < 0) newTop = 0;
if (newLeft < 0) newLeft = 0;
if (newTop > maxTop) newTop = maxTop;
if (newLeft > maxLeft) newLeft = maxLeft;
element.style.top = newTop + "px";
element.style.left = newLeft + "px";
// Update controls position if visible
if (element.classList.contains('selected')) {
showElementControls(element);
}
}
function elementResize(e) {
e.preventDefault();
const rect = element.getBoundingClientRect();
let width, height;
if (currentHandle.classList.contains('bottom-right')) {
width = e.clientX - rect.left;
height = e.clientY - rect.top;
} else if (currentHandle.classList.contains('bottom-left')) {
width = rect.right - e.clientX;
height = e.clientY - rect.top;
element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
} else if (currentHandle.classList.contains('top-right')) {
width = e.clientX - rect.left;
height = rect.bottom - e.clientY;
element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
} else if (currentHandle.classList.contains('top-left')) {
width = rect.right - e.clientX;
height = rect.bottom - e.clientY;
element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
}
if (width > 20 && height > 20) {
element.style.width = width + 'px';
element.style.height = height + 'px';
// For images, adjust the img size
if (element.classList.contains('canvas-media')) {
const img = element.querySelector('img');
img.style.width = '100%';
img.style.height = '100%';
}
// For shapes, adjust SVG size
if (element.classList.contains('canvas-shape')) {
const svg = element.querySelector('svg');
svg.setAttribute('width', width);
svg.setAttribute('height', height);
}
}
// Update controls position if visible
if (element.classList.contains('selected')) {
showElementControls(element);
}
updateCode();
saveState();
}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;
isResizing = false;
currentHandle = null;
updateCode(); // Update code after dragging completes
saveState();
}
}
function addResizeHandles(element) {
const handles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
handles.forEach(handle => {
const div = document.createElement('div');
div.className = 'resize-handle ' + handle;
element.appendChild(div);
});
}
function makeSelectable(element) {
element.addEventListener('click', function(e) {
if (element.dataset.locked === 'true') {
return;
}
e.stopPropagation(); // prevent event bubbling
clearSelection(); // Deselect others
element.classList.add('selected'); // apply selected class
showElementControls(element);
// Update the global opacity slider
const globalOpacity = document.getElementById('globalOpacity');
globalOpacity.value = element.style.opacity * 100;
});
}
function clearSelection() {
document.querySelectorAll('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected').forEach(el => {
el.classList.remove('selected');
});
hideAllControls();
}
function showElementControls(element) {
hideAllControls();
if (element.classList.contains('canvas-text')) {
const controls = document.querySelector(`.text-controls[data-text-id="${element.id}"]`);
if (controls) {
controls.style.display = 'flex';
const canvas = document.getElementById('canvas');
const canvasRect = canvas.getBoundingClientRect();
controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
}
} else if (element.classList.contains('canvas-media')) {
const controls = document.querySelector(`.media-controls[data-media-id="${element.id}"]`);
if (controls) {
controls.style.display = 'flex';
const canvas = document.getElementById('canvas');
const canvasRect = canvas.getBoundingClientRect();
controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
}
} else if (element.classList.contains('canvas-shape')) {
const controls = document.querySelector(`.shape-controls[data-shape-id="${element.id}"]`);
if (controls) {
controls.style.display = 'flex';
const canvas = document.getElementById('canvas');
const canvasRect = canvas.getBoundingClientRect();
controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
}
}
// Show canvas outline
const canvasOutline = document.getElementById('canvasOutline');
canvasOutline.style.display = 'block';
canvasOutline.style.top = `${element.offsetTop - 10}px`;
canvasOutline.style.left = `${element.offsetLeft - 10}px`;
canvasOutline.style.width = `${element.offsetWidth + 20}px`;
canvasOutline.style.height = `${element.offsetHeight + 20}px`;
}
function hideAllControls() {
document.querySelectorAll('.text-controls, .media-controls, .shape-controls').forEach(control => {
control.style.display = 'none';
});
gradientTool.style.display = 'none';
isGradientToolActive = false;
strokeTool.style.display = 'none';
isStrokeToolActive = false;
// Hide canvas outline
const canvasOutline = document.getElementById('canvasOutline');
canvasOutline.style.display = 'none';
}
function addTextControls(textElement) {
const wrapper = document.getElementById('text-controls-wrapper');
const controls = document.createElement('div');
controls.className = 'text-controls';
controls.setAttribute('data-text-id', textElement.id);
controls.style.display = 'none';
controls.innerHTML = `
<button onclick="toggleBold(this, '${textElement.id}')" title="Bold"><i class="material-icons">format_bold</i></button>
<button onclick="toggleItalic(this, '${textElement.id}')" title="Italic"><i class="material-icons">format_italic</i></button>
<button onclick="toggleUnderline(this, '${textElement.id}')" title="Underline"><i class="material-icons">format_underline</i></button>
<input type="color" onchange="changeTextColor(this.value, '${textElement.id}')" title="Text Color">
<input type="number" min="1" max="100" value="16" onchange="changeFontSize(this.value, '${textElement.id}')" title="Font Size">
<select onchange="changeFontFamily(this.value, '${textElement.id}')" title="Font Family">
<option value="Roboto">Roboto</option>
<option value="'Source Sans Pro'">Source Sans Pro</option>
<option value="Arial">Arial</option>
<option value="Helvetica">Helvetica</option>
<option value="'Times New Roman'">Times New Roman</option>
<option value="'Courier New'">Courier New</option>
<option value="Verdana">Verdana</option>
<option value="Georgia">Georgia</option>
<option value="Palatino">Palatino</option>
<option value="Garamond">Garamond</option>
<option value="Bookman">Bookman</option>
<option value="'Comic Sans MS'">Comic Sans MS</option>
<option value="'Trebuchet MS'">Trebuchet MS</option>
<option value="'Arial Black'">Arial Black</option>
</select>
`;
wrapper.appendChild(controls);
}
function addMediaControls(mediaElement) {
const wrapper = document.getElementById('media-controls-wrapper');
const controls = document.createElement('div');
controls.className = 'media-controls';
controls.setAttribute('data-media-id', mediaElement.id);
controls.style.display = 'none';
controls.innerHTML = `
<button onclick="removeMedia('${mediaElement.id}')" title="Remove"><i class="material-icons">delete</i></button>
<button onclick="resetZoom('${mediaElement.id}')" title="Reset Zoom"><i class="material-icons">zoom_out_map</i></button>
`;
wrapper.appendChild(controls);
}
function addShapeControls(shapeElement, shapeType) {
const wrapper = document.getElementById('shape-controls-wrapper');
const controls = document.createElement('div');
controls.className = 'shape-controls';
controls.setAttribute('data-shape-id', shapeElement.id);
controls.style.display = 'none';
controls.innerHTML = `
<button onclick="removeShape('${shapeElement.id}')" title="Remove"><i class="material-icons">delete</i></button>
<button onclick="bringForward('${shapeElement.id}')" title="Bring Forward"><i class="material-icons">arrow_upward</i></button>
<button onclick="sendBackward('${shapeElement.id}')" title="Send Backward"><i class="material-icons">arrow_downward</i></button>
`;
wrapper.appendChild(controls);
}
// Text Control Functions
function changeTextColor(color, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
textContent.style.color = color;
updateCode();
saveState();
}
function changeFontSize(size, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
textContent.style.fontSize = size + 'px';
updateCode();
saveState();
}
function changeFontFamily(family, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
textContent.style.fontFamily = family;
updateCode();
saveState();
}
function toggleBold(button, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
const isBold = textContent.style.fontWeight === 'bold';
textContent.style.fontWeight = isBold ? 'normal' : 'bold';
button.classList.toggle('active', !isBold);
updateCode();
saveState();
}
function toggleItalic(button, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
const isItalic = textContent.style.fontStyle === 'italic';
textContent.style.fontStyle = isItalic ? 'normal' : 'italic';
button.classList.toggle('active', !isItalic);
updateCode();
saveState();
}
function toggleUnderline(button, textId) {
const textElement = document.getElementById(textId);
const textContent = textElement.querySelector('div');
const isUnderline = textContent.style.textDecoration === 'underline';
textContent.style.textDecoration = isUnderline ? 'none' : 'underline';
button.classList.toggle('active', !isUnderline);
updateCode();
saveState();
}
// Media Control Functions
function removeMedia(mediaId) {
const mediaElement = document.getElementById(mediaId);
mediaElement.remove();
const mediaControls = document.querySelector(`.media-controls[data-media-id="${mediaId}"]`);
if (mediaControls) {
mediaControls.style.display = 'none';
}
updateLayerPanel();
updateCode();
saveState();
}
function resetZoom(mediaId) {
const mediaElement = document.getElementById(mediaId);
const img = mediaElement.querySelector('img');
img.style.transform = 'scale(1)';
img.dataset.scale = 1;
// Adjust the container size
mediaElement.style.width = img.naturalWidth + 'px';
mediaElement.style.height = img.naturalHeight + 'px';
updateCode();
saveState();
}
function zoomMedia(img, e) {
e.preventDefault();
const delta = e.deltaY;
const zoomFactor = 0.05; // Smaller zoom factor for smoother zooming
// Get current scale
let scale = img.dataset.scale ? parseFloat(img.dataset.scale) : 1;
// Update scale
scale *= delta > 0 ? (1 - zoomFactor) : (1 + zoomFactor);
// Limit scale
scale = Math.min(Math.max(0.1, scale), 10);
img.dataset.scale = scale;
// Apply scale transform
img.style.transform = `scale(${scale})`;
// Adjust the container size based on the scaled image size
const mediaElement = img.parentElement;
mediaElement.style.width = img.naturalWidth * scale + 'px';
mediaElement.style.height = img.naturalHeight * scale + 'px';
updateCode();
saveState();
}
// Shape Control Functions
function changeShapeColor(color, shapeId) {
const shapeElement = document.getElementById(shapeId);
const svg = shapeElement.querySelector('svg');
const shape = svg.firstChild;
shape.style.fill = color;
updateCode();
saveState();
}
function removeShape(shapeId) {
const shapeElement = document.getElementById(shapeId);
shapeElement.remove();
const shapeControls = document.querySelector(`.shape-controls[data-shape-id="${shapeId}"]`);
if (shapeControls) {
shapeControls.style.display = 'none';
}
updateLayerPanel();
updateCode();
saveState();
}
function bringForward(shapeId) {
const shapeElement = document.getElementById(shapeId);
shapeElement.style.zIndex = (parseInt(shapeElement.style.zIndex) || 1) + 1;
updateLayerPanel();
updateCode();
saveState();
}
function sendBackward(shapeId) {
const shapeElement = document.getElementById(shapeId);
shapeElement.style.zIndex = (parseInt(shapeElement.style.zIndex) || 1) - 1;
updateLayerPanel();
updateCode();
saveState();
}
// Gradient Fill Tool Functions
function toggleGradientTool() {
if (gradientTool.style.display === 'none') {
gradientTool.style.display = 'flex';
updateGradientColors();
updateGradientPreview();
isGradientToolActive = true;
updateSelectedShapeGradient();
} else {
gradientTool.style.display = 'none';
isGradientToolActive = false;
}
}
function addGradientColor() {
gradientColors.push('#ffffff');
updateGradientColors();
updateGradientPreview();
updateSelectedShapeGradient();
}
function updateGradientColors() {
const gradientColorsDiv = document.getElementById('gradientColors');
gradientColorsDiv.innerHTML = '';
gradientColors.forEach((color, index) => {
const colorInput = document.createElement('input');
colorInput.type = 'color';
colorInput.value = color;
colorInput.oninput = function() {
gradientColors[index] = colorInput.value;
updateGradientPreview();
updateSelectedShapeGradient();
};
gradientColorsDiv.appendChild(colorInput);
});
}
function updateGradientPreview() {
const gradientType = document.getElementById('gradientType').value;
const angle = document.getElementById('gradientAngle').value;
const gradientPreview = document.getElementById('gradientPreview');
let gradientString = '';
if (gradientType === 'linear') {
gradientString = `linear-gradient(${angle}deg,${gradientColors.join(', ')})`;
} else if (gradientType === 'radial') {
gradientString = `radial-gradient(${gradientColors.join(', ')})`;
} else if (gradientType === 'conic') {
gradientString = `conic-gradient(${gradientColors.join(', ')})`;
}
gradientPreview.style.background = gradientString;
}
function updateSelectedShapeGradient() {
const selectedElement = document.querySelector('.canvas-shape.selected');
if (selectedElement && isGradientToolActive) {
const gradientType = document.getElementById('gradientType').value;
const angle = document.getElementById('gradientAngle').value;
const colors = gradientColors;
if (selectedElement.classList.contains('canvas-shape')) {
const svg = selectedElement.querySelector('svg');
let defs = svg.querySelector('defs');
if (!defs) {
defs = document.createElementNS(svgNS, 'defs');
svg.appendChild(defs);
}
let gradientId = selectedElement.dataset.gradientId;
if (!gradientId) {
gradientId = `${selectedElement.id}-gradient`;
selectedElement.dataset.gradientId = gradientId;
}
let gradient = document.getElementById(gradientId);
if (gradient) {
defs.removeChild(gradient);
}
if (gradientType === 'linear') {
gradient = document.createElementNS(svgNS, 'linearGradient');
gradient.setAttribute('id', gradientId);
gradient.setAttribute('gradientTransform', `rotate(${angle})`);
} else if (gradientType === 'radial') {
gradient = document.createElementNS(svgNS, 'radialGradient');
gradient.setAttribute('id', gradientId);
// Optionally, adjust radial gradient parameters based on angle
} else if (gradientType === 'conic') {
// SVG does not support conic gradients natively; using linear gradient as a fallback
gradient = document.createElementNS(svgNS, 'linearGradient');
gradient.setAttribute('id', gradientId);
gradient.setAttribute('gradientTransform', `rotate(${angle})`);
}
// Add gradient stops
colors.forEach((color, index) => {
const stop = document.createElementNS(svgNS, 'stop');
const offset = (index / (colors.length - 1)) * 100;
stop.setAttribute('offset', `${offset}%`);
stop.setAttribute('stop-color', color);
gradient.appendChild(stop);
});
defs.appendChild(gradient);
// Apply gradient to shape
const shape = svg.firstChild;
shape.setAttribute('fill', `url(#${gradientId})`);
}
updateCode();
saveState();
}
}
// Stroke Tool Functions
function toggleStrokeTool() {
if (strokeTool.style.display === 'none') {
strokeTool.style.display = 'flex';
updateStrokePreview();
isStrokeToolActive = true;
updateSelectedStroke();
} else {
strokeTool.style.display = 'none';
isStrokeToolActive = false;
}
}
function updateStrokePreview() {
const strokeColor = document.getElementById('strokeColor').value;
const strokePreview = document.getElementById('strokePreview');
strokePreview.style.background = strokeColor;
}
function updateSelectedStroke() {
const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
if (selectedElement && isStrokeToolActive) {
const strokeColor = document.getElementById('strokeColor').value;
const strokeWidth = document.getElementById('strokeWidth').value;
const isContinuous = document.getElementById('continuousStroke').checked;
// Apply stroke
if (selectedElement.classList.contains('canvas-shape')) {
const svg = selectedElement.querySelector('svg');
const shape = svg.firstChild;
shape.setAttribute('stroke', strokeColor);
shape.setAttribute('stroke-width', strokeWidth);
if (!isContinuous) {
// For dashed stroke
shape.setAttribute('stroke-dasharray', '5,5');
} else {
shape.setAttribute('stroke-dasharray', '');
}
} else if (selectedElement.classList.contains('canvas-text')) {
selectedElement.style.border = `${strokeWidth}px solid ${strokeColor}`;
if (!isContinuous) {
// For dashed stroke
selectedElement.style.borderStyle = 'dashed';
} else {
selectedElement.style.borderStyle = 'solid';
}
}
updateStrokePreview();
updateCode();
saveState();
}
}
// Global Opacity Control
function changeGlobalOpacity(value) {
const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
if (selectedElement) {
selectedElement.style.opacity = value / 100;
updateCode();
saveState();
}
}
// Monitor selected element changes to update gradient tools
document.addEventListener('click', function(e) {
// Only update if gradient or stroke tool is active
if (isGradientToolActive) {
const selectedElement = document.querySelector('.canvas-shape.selected');
if (selectedElement) {
updateSelectedShapeGradient();
}
}
if (isStrokeToolActive) {
const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
if (selectedElement) {
updateSelectedStroke();
}
}
});
// Initial save state
saveState();
// Handle click outside to clear selection
document.getElementById('canvas').addEventListener('click', function(e) {
if (e.target === this) {
clearSelection();
}
});
// Code Editor Toggles and Updates
function toggleCode() {
updateCode();
codeArea.style.display = codeArea.style.display === 'block' ? 'none' : 'block';
saveState();
}
function makeElementDraggable(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
elmnt.onmousedown = dragMouseDown;
function dragMouseDown(e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves:
document.onmousemove = elementDrag;
}
function elementDrag(e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position:
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
}
function closeDragElement() {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
updateCode();
saveState();
}
}
makeElementDraggable(codeArea);
makeElementDraggable(document.getElementById('layerPanel'));
makeElementDraggable(document.getElementById('layerPanelHeader'));
function updateCode() {
const canvas = document.getElementById('canvas');
const canvasStyle = getComputedStyle(canvas);
const backgroundColor = canvasStyle.backgroundColor;
const elements = canvas.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
const elementsArray = Array.prototype.map.call(elements, function(element) {
// Clone the element to avoid modifying the original
let clone = element.cloneNode(true);
// Adjust image src attribute for media elements
if (clone.classList.contains('canvas-media')) {
let img = clone.querySelector('img');
if (img) {
let src = img.src;
let fileExtension = '';
if (src.startsWith('data:image/')) {
let match = src.match(/^data:image\/(png|jpeg|jpg);/);
let ext = match ? match[1] : 'png';
if (ext === 'jpeg') ext = 'jpg'; // use jpg instead of jpeg
// Generate 10-digit random number
let randomNumber = Math.floor(1000000000 + Math.random() * 9000000000);
let fileName = randomNumber + '.' + ext;
img.src = fileName;
}
}
}
// Remove selected class and inline styles related to selection
clone.classList.remove('selected');
clone.style.outline = '';
// Remove resize handles
if (clone.classList.contains('canvas-text') || clone.classList.contains('canvas-media') || clone.classList.contains('canvas-shape')) {
const handles = clone.querySelectorAll('.resize-handle');
handles.forEach(handle => handle.remove());
}
// Include transform styles
const computedStyle = window.getComputedStyle(element);
if (computedStyle.transform !== 'none') {
clone.style.transform = computedStyle.transform;
}
// Return the outerHTML of the cloned element
return clone.outerHTML;
});
// Include styles in the code
const styles = document.querySelector('style').outerHTML;
// Build the complete HTML code
let html = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas Export</title>${styles}
</head>
<body>
<div id="canvas" style="background-color:${backgroundColor}; position: relative; width:${canvas.offsetWidth}px; height:${canvas.offsetHeight}px;">${elementsArray.join('\n')}
</div>
</body>
</html>`;
codeElement.textContent = html;
}
// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
const activeElement = document.activeElement;
if (activeElement && (
activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA' ||
activeElement.isContentEditable
)) {
// Don't interfere with typing in input fields or editable divs
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
copyElements();
} else if (e.ctrlKey && (e.key === 'v' || e.key === 'V')) {
e.preventDefault();
pasteElements();
} else if (e.key === 'Delete' || e.key === 'Backspace') {
e.preventDefault();
deleteElement();
} else if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
e.preventDefault();
undo();
} else if (e.ctrlKey && (e.key === 'y' || e.key === 'Y')) {
e.preventDefault();
redo();
}
});
// Undo/Redo functionality
function saveState() {
const canvas = document.getElementById('canvas');
const state = canvas.innerHTML;
undoStack.push(state);
redoStack = []; // Clear redo stack
}
function undo() {
if (undoStack.length > 1) {
redoStack.push(undoStack.pop());
const lastState = undoStack[undoStack.length - 1];
const canvas = document.getElementById('canvas');
canvas.innerHTML = lastState;
reinitializeCanvasElements();
updateLayerPanel();
updateCode();
}
}
function redo() {
if (redoStack.length > 0) {
const state = redoStack.pop();
undoStack.push(state);
const canvas = document.getElementById('canvas');
canvas.innerHTML = state;
reinitializeCanvasElements();
updateLayerPanel();
updateCode();
}
}
function reinitializeCanvasElements() {
const elements = document.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
elements.forEach(element => {
makeDraggable(element);
makeSelectable(element);
if (element.classList.contains('canvas-text')) {
addTextControls(element);
addResizeHandles(element);
} else if (element.classList.contains('canvas-media')) {
addMediaControls(element);
addResizeHandles(element);
const img = element.querySelector('img');
if (img) {
img.onwheel = (e) => {
e.preventDefault();
zoomMedia(img, e);
};
}
} else if (element.classList.contains('canvas-shape')) {
let shapeType = element.dataset.shapeType;
addShapeControls(element, shapeType);
addResizeHandles(element);
}
});
}
// Layer Panel
function updateLayerPanel() {
const layerList = document.getElementById('layerList');
layerList.innerHTML = '';
const canvas = document.getElementById('canvas');
const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
// Reverse to show top layers first
elements.reverse().forEach((element, index) => {
const listItem = document.createElement('li');
listItem.className = 'layer-list-item';
listItem.setAttribute('data-element-id', element.id);
const layerControls = document.createElement('div');
layerControls.className = 'layer-controls';
const visibility = document.createElement('span');
visibility.className = 'layer-visible';
visibility.innerHTML = `<i class="material-icons">${element.style.display === 'none' ? 'visibility_off' : 'visibility'}</i>`;
visibility.addEventListener('click', function(e) {
e.stopPropagation();
toggleVisibility(element.id, visibility);
});
const lock = document.createElement('span');
lock.className = 'layer-lock';
lock.innerHTML = `<i class="material-icons">${element.dataset.locked === 'true' ? 'lock' : 'lock_open'}</i>`;
lock.addEventListener('click', function(e) {
e.stopPropagation();
toggleLock(element.id, lock);
});
layerControls.appendChild(visibility);
layerControls.appendChild(lock);
const thumbnailContainer = document.createElement('div');
thumbnailContainer.className = 'layer-thumbnail';
const thumbnail = document.createElement('canvas');
thumbnail.width = 40;
thumbnail.height = 40;
const ctx = thumbnail.getContext('2d');
if (element.classList.contains('canvas-text')) {
ctx.font = '14px Arial';
ctx.fillStyle = window.getComputedStyle(element.querySelector('div')).color;
ctx.fillText(element.querySelector('div').textContent.trim().substring(0, 10), 2, 15);
} else if (element.classList.contains('canvas-media')) {
const img = element.querySelector('img');
if (img.complete) {
ctx.drawImage(img, 0, 0, 40, 40);
} else {
img.onload = () => {
ctx.drawImage(img, 0, 0, 40, 40);
};
}
} else if (element.classList.contains('canvas-shape')) {
const svg = element.querySelector('svg');
const data = new XMLSerializer().serializeToString(svg);
const DOMURL = window.URL || window.webkitURL || window;
const img = new Image();
const svgBlob = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
const url = DOMURL.createObjectURL(svgBlob);
img.onload = function() {
ctx.drawImage(img, 0, 0, 40, 40);
DOMURL.revokeObjectURL(url);
};
img.src = url;
}
thumbnailContainer.appendChild(thumbnail);
const name = document.createElement('div');
name.className = 'layer-name';
name.textContent = element.id;
listItem.appendChild(layerControls);
listItem.appendChild(thumbnailContainer);
listItem.appendChild(name);
// Add double-click functionality to bring layer forward or send backward
listItem.addEventListener('dblclick', function(e) {
e.stopPropagation();
const zIndices = elements.map(el => parseInt(window.getComputedStyle(el).zIndex) || 1);
const maxZ = Math.max(...zIndices);
const currentZ = parseInt(window.getComputedStyle(element).zIndex) || 1;
element.style.zIndex = maxZ + 1;
updateLayerPanel();
updateCode();
saveState();
});
layerList.appendChild(listItem);
});
makeLayerListDraggable();
}
function makeLayerListDraggable() {
const layerList = document.getElementById('layerList');
const listItems = layerList.querySelectorAll('.layer-list-item');
listItems.forEach(item => {
item.draggable = true;
item.addEventListener('dragstart', dragStart);
item.addEventListener('dragover', dragOver);
item.addEventListener('drop', drop);
});
}
let dragSrcEl = null;
function dragStart(e) {
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
}
function dragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
return false;
}
function drop(e) {
e.stopPropagation();
if (dragSrcEl !== this) {
const layerList = document.getElementById('layerList');
const nodes = Array.from(layerList.children);
const srcIndex = nodes.indexOf(dragSrcEl);
const destIndex = nodes.indexOf(this);
if (srcIndex > destIndex) {
layerList.insertBefore(dragSrcEl, this);
} else {
layerList.insertBefore(dragSrcEl, this.nextSibling);
}
updateCanvasLayerOrder();
}
return false;
}
function updateCanvasLayerOrder() {
const layerList = document.getElementById('layerList');
const layerItems = Array.from(layerList.children);
const canvas = document.getElementById('canvas');
const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
// Remove all elements
elements.forEach(el => {
canvas.removeChild(el);
});
// Re-append in new order based on layerList
layerItems.reverse().forEach(item => { // Reverse to match visual order
const elementId = item.getAttribute('data-element-id');
const element = document.getElementById(elementId);
if (element) {
canvas.appendChild(element);
}
});
updateCode();
saveState();
}
function toggleVisibility(elementId, visibilityIcon) {
const element = document.getElementById(elementId);
if (element.style.display === 'none') {
element.style.display = '';
visibilityIcon.innerHTML = '<i class="material-icons">visibility</i>';
} else {
element.style.display = 'none';
visibilityIcon.innerHTML = '<i class="material-icons">visibility_off</i>';
}
updateCode();
saveState();
}
function toggleLock(elementId, lockIcon) {
const element = document.getElementById(elementId);
if (element.dataset.locked === 'true') {
element.dataset.locked = 'false';
lockIcon.innerHTML = '<i class="material-icons">lock_open</i>';
element.style.pointerEvents = 'auto';
} else {
element.dataset.locked = 'true';
lockIcon.innerHTML = '<i class="material-icons">lock</i>';
element.style.pointerEvents = 'none';
}
updateCode();
saveState();
}
// Copy/Paste/Delete Functions
function copyElements() {
const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
if (selectedElement) {
copiedElement = selectedElement.outerHTML;
}
}
function pasteElements() {
const canvas = document.getElementById('canvas');
if (copiedElement) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = copiedElement;
const element = tempDiv.firstChild;
// Adjust element ID to make it unique
const newId = element.id + '-' + Date.now();
element.id = newId;
// Update gradient ID if it's a shape
if (element.classList.contains('canvas-shape')) {
const oldGradientId = element.dataset.gradientId;
const newGradientId = `${newId}-gradient`;
element.dataset.gradientId = newGradientId;
// Update gradient reference in SVG
const svg = element.querySelector('svg');
const shape = svg.firstChild;
if (shape.getAttribute('fill') && shape.getAttribute('fill').startsWith('url(#')) {
shape.setAttribute('fill', `url(#${newGradientId})`);
}
// Update gradient definitions
const defs = svg.querySelector('defs');
if (defs && oldGradientId) {
const oldGradient = document.getElementById(oldGradientId);
if (oldGradient) {
oldGradient.setAttribute('id', newGradientId);
}
}
}
// Keep the element at the same position
element.style.top = parseInt(element.style.top) + 10 + 'px';
element.style.left = parseInt(element.style.left) + 10 + 'px';
canvas.appendChild(element);
makeDraggable(element);
makeSelectable(element);
if (element.classList.contains('canvas-text')) {
addTextControls(element);
addResizeHandles(element);
} else if (element.classList.contains('canvas-media')) {
addMediaControls(element);
addResizeHandles(element);
const img = element.querySelector('img');
if (img) {
img.onwheel = (e) => {
e.preventDefault();
zoomMedia(img, e);
};
}
} else if (element.classList.contains('canvas-shape')) {
let shapeType = element.dataset.shapeType;
addShapeControls(element, shapeType);
addResizeHandles(element);
}
updateLayerPanel();
updateCode();
saveState();
}
}
function deleteElement() {
const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
if (selectedElement) {
selectedElement.remove();
updateLayerPanel();
updateCode();
saveState();
}
}
// Chat Send Function
function sendMessage(event) {
event.preventDefault();
const input = event.target.querySelector('input');
const message = input.value.trim();
if (message === "") return;
const chatMessages = document.querySelector('.chat-messages');
const newMessage = document.createElement('div');
newMessage.className = 'message';
newMessage.textContent = message;
chatMessages.appendChild(newMessage);
input.value = '';
chatMessages.scrollTop = chatMessages.scrollHeight;
saveState();
}
// Undo/Redo functionality is already implemented above
</script>
</body>
</html>
Explanation of Key Modifications:
-
Gradient Definitions in SVG:
- Each SVG shape now appends a
<defs> element upon creation to hold gradient definitions.
- When applying a gradient, the script creates or updates a
<linearGradient>, <radialGradient>, or falls back to <linearGradient> for conic gradients (since SVG doesn't natively support conic gradients).
- Each gradient has a unique ID based on the shape's ID to ensure individual application.
-
Applying Gradients:
- The
updateSelectedShapeGradient() function handles creating or updating gradients and applies them to the selected shape's fill attribute using url(#gradientId).
- This ensures that gradients are correctly rendered within the SVG context.
-
Single Selection Enforcement:
- The
makeSelectable() function first clears any existing selections before applying the selected class to the clicked element.
- This ensures only one element is selected at any given time, preventing multiple elements from being styled or having gradients applied simultaneously.
-
Live Gradient Updates:
- The gradient tool inputs (
gradientType, gradientAngle, and color inputs) have onchange and oninput event listeners that call updateSelectedShapeGradient().
- This ensures that any changes made in the gradient tool are immediately reflected on the selected shape without requiring additional actions.
-
Unique Gradient IDs for Pasted Shapes:
- When pasting a shape, the script ensures that the gradient ID is updated to reflect the new shape's unique ID. This prevents conflicts and ensures that each shape maintains its own gradient definition.
-
Maintain Selection Outline:
- The
canvasOutline div is updated to match the position and size of the currently selected element, ensuring a clear visual indicator of which element is active.
-
Additional Layer Controls:
- Added "Bring Forward" and "Send Backward" buttons in the shape controls to allow users to adjust the stacking order of shapes.
This updated code ensures that gradients are applied correctly to individual SVG shapes, selections are managed exclusively, and all interactions with gradients and selections are seamless and live-updating. The design and CSS remain unchanged, focusing solely on improving the functionality as per your requirements.