Added the elements array to the react state

This commit is contained in:
André Bastos 2020-01-02 17:04:02 +00:00
parent 70bd7d874f
commit 6ec6e5d82e

View file

@ -4,17 +4,15 @@ import rough from "roughjs/dist/rough.umd.js";
import "./styles.css"; import "./styles.css";
var elements = [];
function isInsideAnElement(x, y) { function isInsideAnElement(x, y) {
return (element) => { return element => {
const x1 = getElementAbsoluteX1(element) const x1 = getElementAbsoluteX1(element);
const x2 = getElementAbsoluteX2(element) const x2 = getElementAbsoluteX2(element);
const y1 = getElementAbsoluteY1(element) const y1 = getElementAbsoluteY1(element);
const y2 = getElementAbsoluteY2(element) const y2 = getElementAbsoluteY2(element);
return (x >= x1 && x <= x2) && (y >= y1 && y <= y2) return x >= x1 && x <= x2 && y >= y1 && y <= y2;
} };
} }
function newElement(type, x, y, width = 0, height = 0) { function newElement(type, x, y, width = 0, height = 0) {
@ -29,16 +27,16 @@ function newElement(type, x, y, width = 0, height = 0) {
return element; return element;
} }
function exportAsPNG({ background, visibleOnly, padding = 10 }) { function exportAsPNG(elements, { background, visibleOnly, padding = 10 }) {
clearSelection(); const clearedElements = clearSelection(elements);
drawScene(); drawScene(clearedElements);
let subCanvasX1 = Infinity; let subCanvasX1 = Infinity;
let subCanvasX2 = 0; let subCanvasX2 = 0;
let subCanvasY1 = Infinity; let subCanvasY1 = Infinity;
let subCanvasY2 = 0; let subCanvasY2 = 0;
elements.forEach(element => { clearedElements.forEach(element => {
subCanvasX1 = Math.min(subCanvasX1, getElementAbsoluteX1(element)); subCanvasX1 = Math.min(subCanvasX1, getElementAbsoluteX1(element));
subCanvasX2 = Math.max(subCanvasX2, getElementAbsoluteX2(element)); subCanvasX2 = Math.max(subCanvasX2, getElementAbsoluteX2(element));
subCanvasY1 = Math.min(subCanvasY1, getElementAbsoluteY1(element)); subCanvasY1 = Math.min(subCanvasY1, getElementAbsoluteY1(element));
@ -47,15 +45,15 @@ function exportAsPNG({ background, visibleOnly, padding = 10 }) {
let targetCanvas = canvas; let targetCanvas = canvas;
if ( visibleOnly ) { if (visibleOnly) {
targetCanvas = document.createElement('canvas'); targetCanvas = document.createElement("canvas");
targetCanvas.style.display = 'none'; targetCanvas.style.display = "none";
document.body.appendChild(targetCanvas); document.body.appendChild(targetCanvas);
targetCanvas.width = subCanvasX2 - subCanvasX1 + padding * 2; targetCanvas.width = subCanvasX2 - subCanvasX1 + padding * 2;
targetCanvas.height = subCanvasY2 - subCanvasY1 + padding * 2; targetCanvas.height = subCanvasY2 - subCanvasY1 + padding * 2;
const targetCanvas_ctx = targetCanvas.getContext('2d'); const targetCanvas_ctx = targetCanvas.getContext("2d");
if ( background ) { if (background) {
targetCanvas_ctx.fillStyle = "#FFF"; targetCanvas_ctx.fillStyle = "#FFF";
targetCanvas_ctx.fillRect(0, 0, canvas.width, canvas.height); targetCanvas_ctx.fillRect(0, 0, canvas.width, canvas.height);
} }
@ -73,12 +71,12 @@ function exportAsPNG({ background, visibleOnly, padding = 10 }) {
); );
} }
const link = document.createElement('a'); const link = document.createElement("a");
link.setAttribute('download', 'excalibur.png'); link.setAttribute("download", "excalibur.png");
link.setAttribute('href', targetCanvas.toDataURL("image/png")); link.setAttribute("href", targetCanvas.toDataURL("image/png"));
link.click(); link.click();
link.remove(); link.remove();
if ( targetCanvas !== canvas ) targetCanvas.remove(); if (targetCanvas !== canvas) targetCanvas.remove();
} }
function rotate(x1, y1, x2, y2, angle) { function rotate(x1, y1, x2, y2, angle) {
@ -185,7 +183,7 @@ function getElementAbsoluteY2(element) {
return element.height >= 0 ? element.y + element.height : element.y; return element.height >= 0 ? element.y + element.height : element.y;
} }
function setSelection(selection) { function setSelection(elements, selection) {
const selectionX1 = getElementAbsoluteX1(selection); const selectionX1 = getElementAbsoluteX1(selection);
const selectionX2 = getElementAbsoluteX2(selection); const selectionX2 = getElementAbsoluteX2(selection);
const selectionY1 = getElementAbsoluteY1(selection); const selectionY1 = getElementAbsoluteY1(selection);
@ -204,14 +202,13 @@ function setSelection(selection) {
}); });
} }
function clearSelection() { function clearSelection(elements) {
elements.forEach(element => { return elements.map(e => ({ ...e, isSelected: false }));
element.isSelected = false;
});
} }
class App extends React.Component { class App extends React.Component {
componentDidMount() { componentDidMount() {
const { elements } = this.state;
this.onKeyDown = event => { this.onKeyDown = event => {
if (event.key === "Backspace" && event.target.nodeName !== "INPUT") { if (event.key === "Backspace" && event.target.nodeName !== "INPUT") {
for (var i = elements.length - 1; i >= 0; --i) { for (var i = elements.length - 1; i >= 0; --i) {
@ -219,7 +216,7 @@ class App extends React.Component {
elements.splice(i, 1); elements.splice(i, 1);
} }
} }
drawScene(); drawScene(elements);
event.preventDefault(); event.preventDefault();
} else if ( } else if (
event.key === "ArrowLeft" || event.key === "ArrowLeft" ||
@ -236,7 +233,7 @@ class App extends React.Component {
else if (event.key === "ArrowDown") element.y += step; else if (event.key === "ArrowDown") element.y += step;
} }
}); });
drawScene(); drawScene(elements);
event.preventDefault(); event.preventDefault();
} }
}; };
@ -250,6 +247,7 @@ class App extends React.Component {
constructor() { constructor() {
super(); super();
this.state = { this.state = {
elements: [],
draggingElement: null, draggingElement: null,
elementType: "selection", elementType: "selection",
exportBackground: false, exportBackground: false,
@ -267,8 +265,8 @@ class App extends React.Component {
checked={this.state.elementType === type} checked={this.state.elementType === type}
onChange={() => { onChange={() => {
this.setState({ elementType: type }); this.setState({ elementType: type });
clearSelection(); clearSelection(this.state.elements);
drawScene(); drawScene(this.state.elements);
}} }}
/> />
{children} {children}
@ -276,185 +274,208 @@ class App extends React.Component {
); );
}; };
return <> return (
<div className="exportWrapper"> <>
<button onClick={() => { <div className="exportWrapper">
exportAsPNG({ <button
background: this.state.exportBackground, onClick={() => {
visibleOnly: this.state.exportVisibleOnly, exportAsPNG(this.state.elements, {
padding: this.state.exportPadding background: this.state.exportBackground,
}) visibleOnly: this.state.exportVisibleOnly,
}}>Export to png</button> padding: this.state.exportPadding
<label> });
<input type="checkbox"
checked={this.state.exportBackground}
onChange={e => {
this.setState({ exportBackground: e.target.checked })
}} }}
/> background >
</label> Export to png
<label> </button>
<input type="checkbox" <label>
checked={this.state.exportVisibleOnly} <input
onChange={e => { type="checkbox"
this.setState({ exportVisibleOnly: e.target.checked }) checked={this.state.exportBackground}
}} onChange={e => {
/> this.setState({ exportBackground: e.target.checked });
visible area only }}
</label> />{" "}
(padding: background
<input type="number" value={this.state.exportPadding} </label>
<label>
<input
type="checkbox"
checked={this.state.exportVisibleOnly}
onChange={e => {
this.setState({ exportVisibleOnly: e.target.checked });
}}
/>
visible area only
</label>
(padding:
<input
type="number"
value={this.state.exportPadding}
onChange={e => { onChange={e => {
this.setState({ exportPadding: e.target.value }); this.setState({ exportPadding: e.target.value });
}} }}
disabled={!this.state.exportVisibleOnly}/> disabled={!this.state.exportVisibleOnly}
px) />
</div> px)
<div> </div>
{/* Can't use the <ElementOption> form because ElementOption is re-defined <div>
{/* Can't use the <ElementOption> form because ElementOption is re-defined
on every render, which would blow up and re-create the entire DOM tree, on every render, which would blow up and re-create the entire DOM tree,
which in addition to being inneficient, messes up with browser text which in addition to being inneficient, messes up with browser text
selection */} selection */}
{ElementOption({ type: "rectangle", children: "Rectangle" })} {ElementOption({ type: "rectangle", children: "Rectangle" })}
{ElementOption({ type: "ellipse", children: "Ellipse" })} {ElementOption({ type: "ellipse", children: "Ellipse" })}
{ElementOption({ type: "arrow", children: "Arrow" })} {ElementOption({ type: "arrow", children: "Arrow" })}
{ElementOption({ type: "text", children: "Text" })} {ElementOption({ type: "text", children: "Text" })}
{ElementOption({ type: "selection", children: "Selection" })} {ElementOption({ type: "selection", children: "Selection" })}
<canvas <canvas
id="canvas" id="canvas"
width={window.innerWidth} width={window.innerWidth}
height={window.innerHeight} height={window.innerHeight}
onMouseDown={e => { onMouseDown={e => {
const x = e.clientX - e.target.offsetLeft; const x = e.clientX - e.target.offsetLeft;
const y = e.clientY - e.target.offsetTop; const y = e.clientY - e.target.offsetTop;
const element = newElement(this.state.elementType, x, y); const element = newElement(this.state.elementType, x, y);
let isDraggingElements = false; let isDraggingElements = false;
const cursorStyle = document.documentElement.style.cursor; const cursorStyle = document.documentElement.style.cursor;
if (this.state.elementType === "selection") { if (this.state.elementType === "selection") {
const selectedElement = elements.find(isInsideAnElement(x, y)) const selectedElement = this.state.elements.find(
isInsideAnElement(x, y)
);
if (selectedElement) { if (selectedElement) {
this.setState({ draggingElement: selectedElement }); this.setState({ draggingElement: selectedElement });
} }
isDraggingElements = elements.some(element => element.isSelected); isDraggingElements = this.state.elements.some(
element => element.isSelected
);
if (isDraggingElements) { if (isDraggingElements) {
document.documentElement.style.cursor = "move"; document.documentElement.style.cursor = "move";
}
}
if (this.state.elementType === "text") {
const text = prompt("What text do you want?");
if (text === null) {
return;
}
element.text = text;
element.font = "20px Virgil";
const font = context.font;
context.font = element.font;
element.measure = context.measureText(element.text);
context.font = font;
const height =
element.measure.actualBoundingBoxAscent +
element.measure.actualBoundingBoxDescent;
// Center the text
element.x -= element.measure.width / 2;
element.y -= element.measure.actualBoundingBoxAscent;
element.width = element.measure.width;
element.height = height;
}
generateDraw(element);
elements.push(element);
if (this.state.elementType === "text") {
this.setState({
draggingElement: null,
elementType: "selection"
});
element.isSelected = true;
} else {
this.setState({ draggingElement: element });
}
let lastX = x;
let lastY = y;
const onMouseMove = e => {
if (isDraggingElements) {
const selectedElements = elements.filter(el => el.isSelected);
if (selectedElements.length) {
const x = e.clientX - e.target.offsetLeft;
const y = e.clientY - e.target.offsetTop;
selectedElements.forEach(element => {
element.x += x - lastX;
element.y += y - lastY;
});
lastX = x;
lastY = y;
drawScene();
return;
} }
} }
// It is very important to read this.state within each move event, if (this.state.elementType === "text") {
// otherwise we would read a stale one! const text = prompt("What text do you want?");
const draggingElement = this.state.draggingElement; if (text === null) {
if (!draggingElement) return; return;
let width = e.clientX - e.target.offsetLeft - draggingElement.x; }
let height = e.clientY - e.target.offsetTop - draggingElement.y; element.text = text;
draggingElement.width = width; element.font = "20px Virgil";
// Make a perfect square or circle when shift is enabled const font = context.font;
draggingElement.height = e.shiftKey ? width : height; context.font = element.font;
element.measure = context.measureText(element.text);
generateDraw(draggingElement); context.font = font;
const height =
if (this.state.elementType === "selection") { element.measure.actualBoundingBoxAscent +
setSelection(draggingElement); element.measure.actualBoundingBoxDescent;
} // Center the text
drawScene(); element.x -= element.measure.width / 2;
}; element.y -= element.measure.actualBoundingBoxAscent;
element.width = element.measure.width;
const onMouseUp = e => { element.height = height;
const { draggingElement, elementType } = this.state
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
document.documentElement.style.cursor = cursorStyle;
// if no element is clicked, clear the selection and redraw
if (draggingElement === null) {
clearSelection()
drawScene();
return
} }
if (elementType === "selection") { generateDraw(element);
if (isDraggingElements) { const newElements = [...this.state.elements, element];
isDraggingElements = false; this.setState({ elements: newElements });
} if (this.state.elementType === "text") {
elements.pop() this.setState({
setSelection(draggingElement); draggingElement: null,
elementType: "selection"
});
element.isSelected = true;
} else { } else {
draggingElement.isSelected = true; this.setState({ draggingElement: element });
} }
this.setState({ let lastX = x;
draggingElement: null, let lastY = y;
elementType: "selection"
});
drawScene();
};
window.addEventListener("mousemove", onMouseMove); const onMouseMove = e => {
window.addEventListener("mouseup", onMouseUp); if (isDraggingElements) {
const selectedElements = this.state.elements.filter(
el => el.isSelected
);
if (selectedElements.length) {
const x = e.clientX - e.target.offsetLeft;
const y = e.clientY - e.target.offsetTop;
selectedElements.forEach(element => {
element.x += x - lastX;
element.y += y - lastY;
});
lastX = x;
lastY = y;
drawScene(this.state.elements);
return;
}
}
drawScene(); // It is very important to read this.state within each move event,
}} // otherwise we would read a stale one!
/> const draggingElement = this.state.draggingElement;
</div> if (!draggingElement) return;
</>; let width = e.clientX - e.target.offsetLeft - draggingElement.x;
let height = e.clientY - e.target.offsetTop - draggingElement.y;
draggingElement.width = width;
// Make a perfect square or circle when shift is enabled
draggingElement.height = e.shiftKey ? width : height;
generateDraw(draggingElement);
if (this.state.elementType === "selection") {
setSelection(this.state.elements, draggingElement);
}
drawScene(this.state.elements);
};
const onMouseUp = e => {
const { draggingElement, elementType } = this.state;
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
document.documentElement.style.cursor = cursorStyle;
// if no element is clicked, clear the selection and redraw
if (draggingElement === null) {
clearSelection(this.state.elements);
drawScene(this.state.elements);
return;
}
if (elementType === "selection") {
if (isDraggingElements) {
isDraggingElements = false;
}
const newElements = this.state.elements;
newElements.pop();
this.setState({
elements: newElements
});
setSelection(this.state.elements, draggingElement);
} else {
draggingElement.isSelected = true;
}
this.setState({
draggingElement: null,
elementType: "selection"
});
drawScene(this.state.elements);
};
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
drawScene(this.state.elements);
}}
/>
</div>
</>
);
} }
} }
@ -468,7 +489,7 @@ const context = canvas.getContext("2d");
// https://stackoverflow.com/questions/13879322/drawing-a-1px-thick-line-in-canvas-creates-a-2px-thick-line/13879402#comment90766599_13879402 // https://stackoverflow.com/questions/13879322/drawing-a-1px-thick-line-in-canvas-creates-a-2px-thick-line/13879402#comment90766599_13879402
context.translate(0.5, 0.5); context.translate(0.5, 0.5);
function drawScene() { function drawScene(elements) {
ReactDOM.render(<App />, rootElement); ReactDOM.render(<App />, rootElement);
context.clearRect(-0.5, -0.5, canvas.width, canvas.height); context.clearRect(-0.5, -0.5, canvas.width, canvas.height);
@ -495,4 +516,4 @@ function drawScene() {
}); });
} }
drawScene(); drawScene([]);