Calculate Corrosion Growth Rate from Weight Loss

Corrosion Growth Rate Calculator: Calculate from Weight Loss body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f8f9fa; color: #333; line-height: 1.6; margin: 0; padding: 0; } .container { max-width: 960px; margin: 20px auto; padding: 20px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); display: flex; flex-direction: column; } header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid #eee; } h1 { color: #004a99; margin-bottom: 10px; } .subtitle { font-size: 1.1em; color: #555; } .loan-calc-container { background-color: #ffffff; padding: 25px; border-radius: 8px; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); margin-bottom: 30px; } .input-group { margin-bottom: 20px; display: flex; flex-direction: column; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #004a99; } .input-group input[type="number"], .input-group input[type="text"], .input-group select { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 1em; } .input-group input[type="number"]:focus, .input-group input[type="text"]:focus, .input-group select:focus { border-color: #004a99; outline: none; box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2); } .input-group .helper-text { font-size: 0.85em; color: #666; margin-top: 5px; } .error-message { color: #dc3545; font-size: 0.85em; margin-top: 5px; display: none; /* Hidden by default */ } .button-group { display: flex; gap: 10px; margin-top: 20px; } button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; transition: background-color 0.3s ease; font-weight: bold; } .btn-calculate { background-color: #004a99; color: white; } .btn-calculate:hover { background-color: #003366; } .btn-reset { background-color: #6c757d; color: white; } .btn-reset:hover { background-color: #5a6268; } .btn-copy { background-color: #28a745; color: white; } .btn-copy:hover { background-color: #218838; } #results { margin-top: 30px; padding: 20px; background-color: #e9ecef; border-radius: 8px; border: 1px solid #dee2e6; } #results h3 { color: #004a99; margin-top: 0; margin-bottom: 15px; } .result-item { margin-bottom: 10px; font-size: 1.1em; } .result-item strong { color: #004a99; } .primary-result { font-size: 1.8em; font-weight: bold; color: #28a745; background-color: #f0fff0; padding: 15px; border-radius: 5px; text-align: center; margin-bottom: 20px; border: 2px dashed #28a745; } .formula-explanation { font-size: 0.9em; color: #555; margin-top: 15px; padding-top: 10px; border-top: 1px solid #eee; } table { width: 100%; border-collapse: collapse; margin-top: 20px; margin-bottom: 30px; } th, td { padding: 10px; text-align: left; border: 1px solid #ddd; } th { background-color: #004a99; color: white; font-weight: bold; } tr:nth-child(even) { background-color: #f2f2f2; } caption { font-size: 1.1em; font-weight: bold; color: #004a99; margin-bottom: 10px; text-align: left; } canvas { display: block; margin: 20px auto; max-width: 100%; border: 1px solid #ccc; border-radius: 4px; } .chart-container { text-align: center; margin-top: 30px; padding: 20px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid #dee2e6; } .chart-container h3 { margin-top: 0; color: #004a99; } .chart-legend { margin-top: 10px; font-size: 0.9em; color: #555; } .chart-legend span { display: inline-block; margin: 0 10px; } .chart-legend .color-box { display: inline-block; width: 12px; height: 12px; margin-right: 5px; vertical-align: middle; } .color-weight-loss { background-color: #004a99; } .color-growth-rate { background-color: #28a745; } /* Article Styling */ main { padding: 20px; background-color: #fff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); margin-top: 20px; } main h2 { color: #004a99; border-bottom: 2px solid #004a99; padding-bottom: 5px; margin-top: 30px; margin-bottom: 15px; } main h3 { color: #004a99; margin-top: 25px; margin-bottom: 10px; } main p, main ul, main ol { margin-bottom: 15px; } main ul, main ol { padding-left: 25px; } main li { margin-bottom: 8px; } .faq-item { margin-bottom: 15px; padding: 10px; background-color: #f0f8ff; border-left: 4px solid #004a99; border-radius: 4px; } .faq-item strong { color: #004a99; display: block; margin-bottom: 5px; } .internal-links { margin-top: 30px; padding: 20px; background-color: #e9ecef; border-radius: 8px; border: 1px solid #dee2e6; } .internal-links h3 { margin-top: 0; color: #004a99; } .internal-links ul { list-style: none; padding: 0; } .internal-links li { margin-bottom: 10px; } .internal-links a { color: #004a99; text-decoration: none; font-weight: bold; } .internal-links a:hover { text-decoration: underline; } .internal-links p { font-size: 0.9em; color: #555; margin-top: 5px; } footer { text-align: center; margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; font-size: 0.9em; color: #777; }

Corrosion Growth Rate Calculator

Calculate Corrosion Growth Rate from Weight Loss Data

Enter the starting weight of the material sample (e.g., in grams).
Enter the weight of the material sample after exposure (e.g., in grams).
Enter the duration of exposure to the corrosive environment (e.g., in days).
Enter the total surface area exposed to corrosion (e.g., in cm²).
Enter the density of the material (e.g., for steel, in g/cm³).

Calculation Results

Weight Loss:
Corrosion Rate (mm/year):
Corrosion Rate (mils/year):
Formula Used:
Corrosion Rate = (Weight Loss / (Area * Density)) / Exposure Time
This is then converted to standard units like mm/year and mils/year.

Corrosion Data Visualization

Weight Loss (g) Corrosion Rate (mm/year)
Corrosion Analysis Summary
Metric Value Unit
Initial Weight g
Final Weight g
Weight Loss g
Exposure Time days
Exposed Area cm²
Material Density g/cm³
Corrosion Rate (mm/year) mm/year
Corrosion Rate (mils/year) mils/year

What is Corrosion Growth Rate from Weight Loss?

Corrosion growth rate from weight loss is a critical metric used in materials science and engineering to quantify the rate at which a material degrades due to chemical or electrochemical reactions with its environment. Essentially, it measures how much material is lost over a specific period due to corrosion. This method is one of the most straightforward and widely used techniques for assessing corrosion performance, especially in laboratory settings or for initial material screening. It provides a direct, empirical measure of material loss, which can then be extrapolated to predict long-term behavior and estimate the remaining service life of components or structures. Understanding this rate is paramount for industries ranging from aerospace and automotive to construction and chemical processing, where material integrity is directly linked to safety, reliability, and economic viability.

Who should use it: This calculation is vital for materials engineers, corrosion specialists, researchers, quality control managers, and asset integrity engineers. Anyone involved in selecting materials for specific environments, testing the effectiveness of protective coatings, or assessing the degradation of existing infrastructure can benefit from understanding and calculating corrosion growth rates. It's also useful for manufacturers who need to guarantee the durability of their products under various conditions.

Common misconceptions: A common misconception is that weight loss is the only indicator of corrosion. While it's a primary measure, the *rate* of weight loss is what truly defines the growth rate. Another misconception is that a low weight loss always means a material is immune to corrosion; it might simply be corroding very slowly or in a way that doesn't significantly reduce weight (e.g., surface discoloration without material removal). Furthermore, the calculated rate is specific to the tested conditions and may not directly translate to different environments without further analysis.

Corrosion Growth Rate from Weight Loss Formula and Mathematical Explanation

The fundamental principle behind calculating corrosion growth rate from weight loss is to determine the amount of material lost per unit area per unit time. This is achieved by measuring the initial and final weights of a sample, the duration of its exposure to a corrosive environment, the exposed surface area, and the material's density.

The process involves several steps:

  1. Calculate Weight Loss: Subtract the final weight from the initial weight.
  2. Calculate Corrosion Penetration Rate: This is the thickness of material lost per unit time. It's derived by considering the weight loss, the exposed area, and the material's density. The formula is:
    Corrosion Penetration Rate = (Weight Loss / Exposed Area) / Material Density
  3. Convert to Standard Units: The penetration rate is then converted into standard corrosion rate units, most commonly millimeters per year (mm/year) or mils per year (mpy, where 1 mil = 0.001 inches). This conversion requires accounting for the exposure time and the desired time unit (year).

The primary formula used in this calculator is:

Corrosion Rate (in units of mass/area/time) = (Initial Weight – Final Weight) / (Exposed Surface Area * Exposure Time)

To convert this to a linear penetration rate (thickness loss per year), we use the material's density:

Penetration Rate (e.g., g/cm²/day) = Weight Loss (g) / (Exposed Area (cm²) * Exposure Time (days))

Then, to get mm/year:

Corrosion Rate (mm/year) = [Penetration Rate (g/cm²/day) * (1 / Density (g/cm³))] * (365 days/year) * (1 cm / 10 mm)

And to get mils/year (MPY):

Corrosion Rate (mpy) = Corrosion Rate (mm/year) * (1000 mils / 25.4 mm)

Variables Table

Variable Meaning Unit Typical Range
Initial Weight Starting mass of the material sample. grams (g) 1 – 1000+ g
Final Weight Mass of the material sample after exposure. grams (g) 0 – Initial Weight g
Weight Loss Difference between initial and final weight, indicating material lost. grams (g) 0 – Initial Weight g
Exposure Time Duration the material was subjected to the corrosive environment. days (d) 1 – 365+ d
Exposed Surface Area The total surface area of the sample that was in contact with the corrosive medium. square centimeters (cm²) 1 – 1000+ cm²
Material Density Mass per unit volume of the material being tested. Crucial for converting weight loss to thickness loss. grams per cubic centimeter (g/cm³) 0.7 – 22.5 g/cm³ (e.g., Aluminum ~2.7, Steel ~7.87, Gold ~19.3)
Corrosion Rate (mm/year) Linear rate of material thickness loss per year. millimeters per year (mm/year) 0.001 – 10+ mm/year (highly variable)
Corrosion Rate (mpy) Linear rate of material thickness loss per year, in mils (thousandths of an inch). mils per year (mpy) 0.04 – 400+ mpy (highly variable)

Practical Examples (Real-World Use Cases)

Example 1: Steel in a Salty Environment

A steel sample is exposed to a marine environment for 90 days.

  • Initial Weight: 250 g
  • Final Weight: 245 g
  • Exposure Time: 90 days
  • Exposed Surface Area: 100 cm²
  • Material Density (Steel): 7.87 g/cm³

Calculation:

  • Weight Loss = 250 g – 245 g = 5 g
  • Penetration Rate (g/cm²/day) = 5 g / (100 cm² * 90 days) = 0.000556 g/cm²/day
  • Corrosion Rate (mm/year) = [0.000556 g/cm²/day * (1 / 7.87 g/cm³)] * (365 days/year) * (1 cm / 10 mm) ≈ 0.258 mm/year
  • Corrosion Rate (mpy) = 0.258 mm/year * (1000 mils / 25.4 mm) ≈ 10.16 mpy

Interpretation: This steel sample is corroding at a rate of approximately 0.26 mm per year, or about 10 mils per year. This rate might be acceptable for some applications but could be too high for critical structural components in a marine environment, suggesting the need for protective coatings or alternative materials.

Example 2: Aluminum Alloy in an Acidic Solution

An aluminum alloy sample is tested in a specific acidic solution for 15 days.

  • Initial Weight: 50 g
  • Final Weight: 49.2 g
  • Exposure Time: 15 days
  • Exposed Surface Area: 25 cm²
  • Material Density (Aluminum Alloy): 2.7 g/cm³

Calculation:

  • Weight Loss = 50 g – 49.2 g = 0.8 g
  • Penetration Rate (g/cm²/day) = 0.8 g / (25 cm² * 15 days) = 0.002133 g/cm²/day
  • Corrosion Rate (mm/year) = [0.002133 g/cm²/day * (1 / 2.7 g/cm³)] * (365 days/year) * (1 cm / 10 mm) ≈ 2.91 mm/year
  • Corrosion Rate (mpy) = 2.91 mm/year * (1000 mils / 25.4 mm) ≈ 114.5 mpy

Interpretation: The aluminum alloy shows a significantly higher corrosion rate of approximately 2.9 mm per year (or 115 mpy) in this acidic environment. This indicates that the alloy is not suitable for prolonged exposure to this specific acid and would likely fail prematurely. This result highlights the importance of material compatibility testing.

How to Use This Corrosion Growth Rate Calculator

Using the Corrosion Growth Rate Calculator is straightforward. Follow these steps to get accurate results:

  1. Gather Your Data: You will need the following precise measurements from your corrosion test:
    • The initial weight of your material sample.
    • The final weight of the sample after the exposure period.
    • The total duration the sample was exposed to the corrosive environment.
    • The exact surface area of the sample that was exposed.
    • The known density of the material you are testing.
  2. Input Values: Enter each piece of data into the corresponding field in the calculator. Ensure you use consistent units (e.g., grams for weight, cm² for area, days for time, g/cm³ for density). The calculator is pre-filled with example values to demonstrate its use.
  3. Validate Inputs: The calculator performs inline validation. If you enter non-numeric values, negative numbers where they are not allowed, or leave fields blank, an error message will appear below the respective input field. Correct any errors before proceeding.
  4. Calculate: Click the "Calculate" button. The calculator will process your inputs and display the results.
  5. Interpret Results:
    • Primary Result: The main highlighted number shows the calculated corrosion rate, typically in mm/year or mpy, which is the most common way to express linear corrosion.
    • Intermediate Values: You'll see the calculated weight loss and the corrosion rate in both mm/year and mils/year for comprehensive understanding.
    • Formula Explanation: A brief description of the underlying formula is provided for clarity.
    • Table: A summary table presents all input values and calculated results for easy review.
    • Chart: A dynamic chart visualizes the weight loss and the calculated corrosion rate, helping to understand the trend.
  6. Reset or Copy:
    • Click "Reset" to clear the fields and return them to their default values.
    • Click "Copy Results" to copy the key calculated metrics and assumptions to your clipboard for use in reports or other documents.

Decision-making guidance: Compare the calculated corrosion rate against industry standards, material specifications, or acceptable limits for your application. A high corrosion rate may indicate that the material is unsuitable for the environment, or that protective measures (like coatings or inhibitors) are necessary. Conversely, a low rate suggests good performance.

Key Factors That Affect Corrosion Growth Rate Results

The corrosion growth rate calculated from weight loss is influenced by numerous factors. Understanding these is crucial for accurate testing and interpretation:

  • Environmental Conditions: This is the most significant factor. Temperature, humidity, pH, the presence of specific ions (like chlorides or sulfates), oxygen concentration, and flow rate of the corrosive medium all dramatically impact corrosion kinetics. Higher temperatures generally accelerate corrosion.
  • Material Composition and Microstructure: The specific alloy, its purity, grain size, presence of inclusions, and heat treatment history affect its susceptibility to corrosion. Different phases within an alloy can lead to galvanic corrosion.
  • Surface Preparation: The initial condition of the material surface (e.g., polished, as-received, scaled) can influence the starting point of corrosion. A rougher surface might offer more sites for corrosion initiation.
  • Sample Geometry and Area Measurement Accuracy: Precise measurement of the exposed surface area is critical. Complex geometries can lead to uneven corrosion, and inaccurate area measurements will directly skew the calculated rate.
  • Test Duration: Short-term tests might not reveal the long-term corrosion behavior. Some corrosion processes are rapid initially and then slow down (passivation), while others might accelerate over time. The chosen duration must be representative.
  • Presence of Protective Films or Coatings: If the material naturally forms a passive oxide layer, or if a protective coating is applied, this will significantly reduce the measured weight loss and corrosion rate. The integrity and effectiveness of these films are key.
  • Galvanic Effects: If the sample is in contact with another dissimilar metal in the corrosive electrolyte, galvanic corrosion can occur, leading to accelerated corrosion of the less noble metal. This calculator assumes a single material.
  • Biological Factors: In some environments, microorganisms can influence corrosion rates (microbially influenced corrosion – MIC), which is not directly accounted for by simple weight loss measurements unless the biological activity is the primary driver of chemical change.

Frequently Asked Questions (FAQ)

Q1: What is the difference between weight loss and corrosion growth rate?

Weight loss is the absolute amount of material lost (e.g., in grams). Corrosion growth rate is a measure of how quickly this loss occurs, typically expressed as a rate per unit time (e.g., mm/year or mpy), and often normalized by surface area and material density to represent thickness loss.

Q2: Can this calculator be used for all types of corrosion?

This calculator specifically measures corrosion based on weight loss. It's most effective for uniform corrosion where material is lost evenly across the surface. It may not accurately represent localized corrosion like pitting or crevice corrosion, where significant damage can occur with minimal overall weight loss.

Q3: What units should I use for input?

The calculator is designed to work with grams (g) for weight, days (d) for time, square centimeters (cm²) for area, and grams per cubic centimeter (g/cm³) for density. The output will be in mm/year and mils/year. Ensure your input data is converted to these units before entering.

Q4: What if my material gains weight?

Weight gain during exposure usually indicates the formation of a stable, adherent corrosion product layer (like some oxides or scales) that adds mass. This calculator assumes weight loss due to material degradation. If weight gain occurs, the calculated "weight loss" will be negative, leading to a negative corrosion rate, which indicates material gain rather than loss. This scenario requires a different interpretation and might suggest passivation or scale formation.

Q5: How accurate is the corrosion rate calculation?

The accuracy depends heavily on the precision of your input measurements (weights, time, area) and the representativeness of the test conditions. The calculation itself is mathematically sound, but the real-world applicability relies on good experimental data.

Q6: What is a "good" or "bad" corrosion rate?

There is no universal "good" or "bad" rate. It depends entirely on the application, the material, the environment, and the expected service life. A rate of 0.1 mm/year might be unacceptable for a critical aerospace component but perfectly fine for a temporary structure. Industry standards and material specifications define acceptable limits.

Q7: Does the calculator account for temperature effects?

No, this calculator does not directly take temperature as an input. However, the *effect* of temperature is implicitly included if your measured weight loss occurred under specific, consistent temperature conditions. If temperature varies significantly, the calculated rate represents an average over the test period. For precise analysis, tests should be conducted at controlled, relevant temperatures.

Q8: How can I reduce corrosion growth rate?

Reducing corrosion growth rate typically involves:

  • Selecting more corrosion-resistant materials.
  • Applying protective coatings (paints, platings, galvanizing).
  • Using corrosion inhibitors.
  • Controlling the environment (e.g., reducing humidity, removing contaminants).
  • Implementing cathodic or anodic protection systems.

© 2023 Your Company Name. All rights reserved.

var chartInstance = null; // Global variable to hold chart instance function validateInput(id, minValue = null, maxValue = null) { var input = document.getElementById(id); var errorDiv = document.getElementById(id + 'Error'); var value = parseFloat(input.value); errorDiv.style.display = 'none'; // Hide error by default if (input.value === ") { errorDiv.textContent = 'This field cannot be empty.'; errorDiv.style.display = 'block'; return false; } if (isNaN(value)) { errorDiv.textContent = 'Please enter a valid number.'; errorDiv.style.display = 'block'; return false; } if (minValue !== null && value maxValue) { errorDiv.textContent = 'Value cannot exceed ' + maxValue + '.'; errorDiv.style.display = 'block'; return false; } return true; } function calculateCorrosion() { var isValid = true; isValid &= validateInput('initialWeight', 0); isValid &= validateInput('finalWeight', 0); isValid &= validateInput('exposureTime', 0.0001); // Must be greater than 0 isValid &= validateInput('sampleArea', 0.0001); // Must be greater than 0 isValid &= validateInput('materialDensity', 0.0001); // Must be greater than 0 if (!isValid) { document.getElementById('primaryResult').textContent = 'Invalid Input'; document.getElementById('weightLoss').textContent = '–'; document.getElementById('corrosionRateMMY').textContent = '–'; document.getElementById('corrosionRateMPY').textContent = '–'; updateTable('–', '–', '–', '–', '–', '–', '–', '–'); updateChart([], []); return; } var initialWeight = parseFloat(document.getElementById('initialWeight').value); var finalWeight = parseFloat(document.getElementById('finalWeight').value); var exposureTime = parseFloat(document.getElementById('exposureTime').value); var sampleArea = parseFloat(document.getElementById('sampleArea').value); var materialDensity = parseFloat(document.getElementById('materialDensity').value); var weightLoss = initialWeight – finalWeight; if (weightLoss < 0) { // Handle weight gain scenario – indicate it clearly document.getElementById('primaryResult').textContent = 'Weight Gain Detected'; document.getElementById('weightLoss').textContent = weightLoss.toFixed(4) + ' g'; document.getElementById('corrosionRateMMY').textContent = 'N/A (Gain)'; document.getElementById('corrosionRateMPY').textContent = 'N/A (Gain)'; updateTable(initialWeight, finalWeight, weightLoss.toFixed(4), exposureTime, sampleArea, materialDensity, 'N/A (Gain)', 'N/A (Gain)'); updateChart([weightLoss], [0]); // Show weight loss, rate is 0 or N/A return; } // Calculate corrosion rate in g/cm²/day var corrosionRatePerDay = weightLoss / (sampleArea * exposureTime); // Convert to mm/year // 1 g/cm²/day * (1 cm³/g / density g/cm³) * (365 day/year) * (1 cm / 10 mm) var corrosionRateMMY = (corrosionRatePerDay / materialDensity) * 365 * (1 / 10); // Convert mm/year to mils/year (MPY) // 1 inch = 25.4 mm, 1 mil = 0.001 inch = 0.0254 mm // mm/year * (1 mil / 0.0254 mm) var corrosionRateMPY = corrosionRateMMY * (1 / 0.0254); document.getElementById('primaryResult').textContent = corrosionRateMMY.toFixed(3) + ' mm/year'; document.getElementById('weightLoss').textContent = weightLoss.toFixed(4) + ' g'; document.getElementById('corrosionRateMMY').textContent = corrosionRateMMY.toFixed(3) + ' mm/year'; document.getElementById('corrosionRateMPY').textContent = corrosionRateMPY.toFixed(2) + ' mpy'; updateTable(initialWeight, finalWeight, weightLoss.toFixed(4), exposureTime, sampleArea, materialDensity, corrosionRateMMY.toFixed(3), corrosionRateMPY.toFixed(2)); updateChart([weightLoss], [corrosionRateMMY]); } function updateTable(initialWeight, finalWeight, weightLoss, exposureTime, sampleArea, materialDensity, corrosionRateMMY, corrosionRateMPY) { document.getElementById('tableInitialWeight').textContent = initialWeight === '–' ? '–' : initialWeight.toFixed(2); document.getElementById('tableFinalWeight').textContent = finalWeight === '–' ? '–' : finalWeight.toFixed(2); document.getElementById('tableWeightLoss').textContent = weightLoss; document.getElementById('tableExposureTime').textContent = exposureTime === '–' ? '–' : exposureTime.toFixed(1); document.getElementById('tableArea').textContent = sampleArea === '–' ? '–' : sampleArea.toFixed(2); document.getElementById('tableDensity').textContent = materialDensity === '–' ? '–' : materialDensity.toFixed(2); document.getElementById('tableCorrosionRateMMY').textContent = corrosionRateMMY; document.getElementById('tableCorrosionRateMPY').textContent = corrosionRateMPY; } function updateChart(weightLossData, corrosionRateData) { var ctx = document.getElementById('corrosionChart').getContext('2d'); // Destroy previous chart instance if it exists if (chartInstance) { chartInstance.destroy(); } var labels = ['Initial', 'After Exposure']; var dataWeightLoss = [parseFloat(document.getElementById('initialWeight').value), parseFloat(document.getElementById('finalWeight').value)]; var dataCorrosionRate = [0, parseFloat(corrosionRateData[0]) || 0]; // Use calculated rate, default to 0 if N/A // Adjust data points for visualization // We'll show initial weight, final weight, and a representative corrosion rate point var chartLabels = ['Initial State', 'Final State']; var chartWeightData = [ parseFloat(document.getElementById('initialWeight').value), parseFloat(document.getElementById('finalWeight').value) ]; var chartRateData = [0, parseFloat(corrosionRateData[0]) || 0]; // Rate is 0 at start, calculated at end // If weight gain, set rate to 0 or indicate differently if (weightLossData[0] < 0) { chartRateData = [0, 0]; // No corrosion rate if weight gain } chartInstance = new Chart(ctx, { type: 'bar', // Use bar chart for weight, line for rate data: { labels: chartLabels, datasets: [{ label: 'Sample Weight (g)', data: chartWeightData, backgroundColor: 'rgba(0, 74, 153, 0.6)', // Primary color borderColor: 'rgba(0, 74, 153, 1)', borderWidth: 1, yAxisID: 'y-axis-weight' }, { label: 'Corrosion Rate (mm/year)', data: chartRateData, type: 'line', // Line chart for rate borderColor: 'rgba(40, 167, 69, 1)', // Success color backgroundColor: 'rgba(40, 167, 69, 0.2)', fill: false, tension: 0.1, yAxisID: 'y-axis-rate' }] }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { title: { display: true, text: 'Measurement Point' } }, 'y-axis-weight': { type: 'linear', position: 'left', title: { display: true, text: 'Weight (g)' }, ticks: { beginAtZero: true } }, 'y-axis-rate': { type: 'linear', position: 'right', title: { display: true, text: 'Corrosion Rate (mm/year)' }, ticks: { beginAtZero: true }, grid: { drawOnChartArea: false, // Only draw grid lines for the primary y-axis } } }, plugins: { tooltip: { mode: 'index', intersect: false } } } }); } function resetCalculator() { document.getElementById('initialWeight').value = '100'; document.getElementById('finalWeight').value = '98'; document.getElementById('exposureTime').value = '30'; document.getElementById('sampleArea').value = '50'; document.getElementById('materialDensity').value = '7.87'; // Clear errors document.getElementById('initialWeightError').textContent = ''; document.getElementById('finalWeightError').textContent = ''; document.getElementById('exposureTimeError').textContent = ''; document.getElementById('sampleAreaError').textContent = ''; document.getElementById('materialDensityError').textContent = ''; calculateCorrosion(); // Recalculate with default values } function copyResults() { var primaryResult = document.getElementById('primaryResult').textContent; var weightLoss = document.getElementById('weightLoss').textContent; var corrosionRateMMY = document.getElementById('corrosionRateMMY').textContent; var corrosionRateMPY = document.getElementById('corrosionRateMPY').textContent; var initialWeight = document.getElementById('initialWeight').value; var finalWeight = document.getElementById('finalWeight').value; var exposureTime = document.getElementById('exposureTime').value; var sampleArea = document.getElementById('sampleArea').value; var materialDensity = document.getElementById('materialDensity').value; var resultsText = "— Corrosion Growth Rate Calculation Results —\n\n"; resultsText += "Primary Result: " + primaryResult + "\n"; resultsText += "Weight Loss: " + weightLoss + "\n"; resultsText += "Corrosion Rate (mm/year): " + corrosionRateMMY + "\n"; resultsText += "Corrosion Rate (mils/year): " + corrosionRateMPY + "\n\n"; resultsText += "— Key Assumptions & Inputs —\n"; resultsText += "Initial Weight: " + initialWeight + " g\n"; resultsText += "Final Weight: " + finalWeight + " g\n"; resultsText += "Exposure Time: " + exposureTime + " days\n"; resultsText += "Exposed Surface Area: " + sampleArea + " cm²\n"; resultsText += "Material Density: " + materialDensity + " g/cm³\n"; // Use a temporary textarea to copy text var textArea = document.createElement("textarea"); textArea.value = resultsText; document.body.appendChild(textArea); textArea.select(); try { document.execCommand("copy"); alert("Results copied to clipboard!"); } catch (err) { console.error("Failed to copy results: ", err); alert("Failed to copy results. Please copy manually."); } document.body.removeChild(textArea); } // Initial calculation on page load document.addEventListener('DOMContentLoaded', function() { calculateCorrosion(); // Load Chart.js library dynamically if not already present if (typeof Chart === 'undefined') { var script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js'; script.onload = function() { console.log('Chart.js loaded.'); // Ensure initial calculation happens after chart library is loaded if needed calculateCorrosion(); }; document.head.appendChild(script); } else { calculateCorrosion(); // Calculate immediately if Chart.js is already available } });

Leave a Comment