Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Snap2Code #439

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions Snap2Code
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import html2canvas from 'html2canvas';

// Define the interface for the element attributes
interface ScreenshotElement {
tag: string;
styles: Record<string, string>;
content: string;
}

// Function to take a screenshot of an HTML element and generate code
async function screenshotToCode(elementId: string): Promise<string> {
const element = document.getElementById(elementId);
if (!element) {
throw new Error("Element not found");
}

// Capture the screenshot as a canvas
const canvas = await html2canvas(element);
const dataUrl = canvas.toDataURL();

// Convert the visual element into HTML code
const screenshotElements: ScreenshotElement[] = extractElementDetails(element);

let generatedCode = `
<div id="${elementId}" style="background-image: url(${dataUrl});">
`;
screenshotElements.forEach(({ tag, styles, content }) => {
const styleString = Object.entries(styles)
.map(([key, value]) => `${key}:${value}`)
.join('; ');
generatedCode += `<${tag} style="${styleString}">${content}</${tag}>`;
});
generatedCode += '</div>';

return generatedCode;
}

// Function to extract element details (basic example for div, p, and h tags)
function extractElementDetails(element: HTMLElement): ScreenshotElement[] {
const elements: ScreenshotElement[] = [];
const childNodes = Array.from(element.childNodes);

childNodes.forEach((childNode) => {
if (childNode instanceof HTMLElement) {
const styles = window.getComputedStyle(childNode);
const styleObj: Record<string, string> = {};
for (let i = 0; i < styles.length; i++) {
const property = styles[i];
styleObj[property] = styles.getPropertyValue(property);
}

elements.push({
tag: childNode.tagName.toLowerCase(),
styles: styleObj,
content: childNode.innerHTML.trim() || childNode.textContent || '',
});
}
});

return elements;
}

// Example usage:
async function generateCodeFromScreenshot() {
try {
const code = await screenshotToCode('target-element');
console.log('Generated Code:', code);
} catch (error) {
console.error('Error:', error);
}
}

// Call the function with a sample element ID
generateCodeFromScreenshot();