Files
personal_development/gift_app/static/script.js
T
2026-01-03 13:30:35 -05:00

62 lines
2.4 KiB
JavaScript

document.getElementById('generateBtn').addEventListener('click', function() {
console.log("Button clicked, fetching word data...");
// Show a temporary loading message
const cloudDiv = document.getElementById('wordcloud');
cloudDiv.innerHTML = '<p>Generating... please wait.</p>';
fetch('/get-word-data')
.then(response => response.json())
.then(data => {
console.log("Data received from backend:", data);
generateCloud(data);
})
.catch(error => {
console.error('Error fetching word data:', error);
cloudDiv.innerHTML = '<p>Could not load word data. Is the server running?</p>';
});
});
function generateCloud(words) {
// Clear the loading message
const cloudDiv = document.getElementById('wordcloud');
cloudDiv.innerHTML = '';
const width = 800;
const height = 400;
// Create a color scale. Words with a higher gift_score get a gold color.
const colorScale = d3.scale.linear()
.domain([0, 1, 2, 3, 5]) // Corresponds to gift_score
.range(["#606770", "#1877f2", "#f5b400", "#f5b400", "#ff8c00"]); // Grey -> Blue -> Gold -> Orange
// The main word cloud layout logic
d3.layout.cloud().size([width, height])
.words(words)
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; }) // 0 or 90 degrees rotation
.font("Impact")
.fontSize(function(d) { return 10 + Math.sqrt(d.size) * 5; }) // Scale font size
.on("end", draw)
.start();
// This function is called when the layout algorithm finishes
function draw(words) {
d3.select("#wordcloud").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d) { return colorScale(d.gift_score); })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
}