-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
84 lines (76 loc) · 2.23 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const getPokemon = async (pokemonName) => {
return fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`)
.then((response) => response.json())
.catch((error) => error);
}
const configureChartData = (stats, pokemonName) => {
const baseStats = stats.map((stat) => stat.base_stat);
const [hp, atk, def, spAtk, spDef, speed] = baseStats;
return {
labels: ['HP', 'Attack', 'Special Attack', 'Speed', 'Special Defense', 'Defense'],
datasets: [{
label: `${pokemonName}`,
data: [hp, atk, spAtk, speed, spDef, def],
fill: true,
backgroundColor: 'rgb(3, 4, 94, 0.2)',
borderColor: '#03045eff',
pointBackgroundColor: '#fff',
pointBorderColor: '#03045eff',
pointHoverBackgroundColor: '#03045eff',
// pointHoverBorderColor: '#fff'
}]
}
};
const configureChart = (stats, pokemonName) => {
return {
type: 'radar',
data: configureChartData(stats, pokemonName),
options: {
elements: {
line: {
borderWidth: 3
}
},
plugins: {
title: {
display: true,
text: `${pokemonName} Base Stats`
}
}
},
}
};
const addEventButton = () => {
const button = document.querySelector('button');
button.addEventListener('click', fetchPokemon)
}
const fetchPokemon = async () => {
try {
const chart = document.getElementById('myChart');
if (chart) chart.remove();
const inputText = document.querySelector('input').value.toLowerCase();
const pokemon = await getPokemon(inputText);
renderChart(pokemon);
} catch (error) {
alert('Pokémon inválido');
}
}
const createCanvas = () => {
const chartContainer = document.getElementById('chart-container');
const canvas = document.createElement('canvas');
canvas.id = 'myChart';
chartContainer.appendChild(canvas);
return canvas;
}
const renderChart = (pokemon) => {
//pokemon request
const { stats, name } = pokemon;
const nameCapitalizing = name.replace(/^\w/, name[0].toUpperCase());
//create new chart
const newCanvas = createCanvas();
const chartConfigurations = configureChart(stats, nameCapitalizing);
const myChart = new Chart(newCanvas, chartConfigurations);
};
window.onload = () => {
addEventButton();
};