Last active
December 25, 2019 05:33
-
-
Save pflevy/ef92b73cb36880c4be6c031065e8e757 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef, useEffect } from "react"; | |
// The CanvasBucket component receives the distance value from it's parent component | |
const CanvasBucket = ({ distance }) => { | |
// Define the maximum liters the tank supports, the drawing will look full | |
const maximumLiters = 10; | |
// Reference the canvas HTML5 object | |
const canvasRef = useRef(null); | |
// Use effect trigers a function every time it's depencies (speficied on []) changes, | |
// In this case, when distance changes, useEffects triggers the function to draw on screen | |
useEffect(() => { | |
// Getting the canvas referece declared above | |
const canvas = canvasRef.current; | |
// ctx (context) will be the variable to create 2d graphics on the canvas element | |
const ctx = canvas.getContext("2d"); | |
// Clears any previus drawing on the canvas as the drawing will be recurrent | |
ctx.clearRect(0, 0, canvas.width, canvas.height); | |
// Creates a drawing start point | |
ctx.beginPath(); | |
// Starting at 10 all the way to 170, there are 160px to fill the maximum liquid. 10 = Maximum L | |
let multiplier = 160 / 10; | |
ctx.fillStyle = "#6464ff"; | |
ctx.rect(10, 170, 120, -multiplier * distance); | |
ctx.fill(); | |
}, [distance]); | |
return <canvas ref={canvasRef} width={140} height={180} />; | |
}; | |
export default CanvasBucket; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your article here https://medium.com/swlh/real-time-iot-app-with-react-firebase-esp8266-e2e673efd1bf does not include this code, and contains 2 app.js codes in it. Just thought you should know. Very helpful tutorial by the way.