How To Change Drawing Colors In HTML5 Canvas
JavaScript
22/05/2021
Changing colors of a stroke isn't 🚀 rocket science. All you have to do is set the strokeStyle
property to a color of your choosing.
JAVASCRIPT
const context = canvas.getContext('2d')context.strokeStyle = 'red'
However, let's keep things interesting by adding some buttons that change the color for you.
Adding color buttons
HTML
<button>Black</button><button>Blue</button><button>Red</button>
Since we want to trigger a color change upon clicking a button, we have to listen to the click
event with a function called changeColor
.
HTML
<button onclick='changeColor("black")'>Black</button><button onclick='changeColor("blue")'>Blue</button><button onclick='changeColor("red")'>Red</button>
Then, in our function, we simply use the passed in color value and assign it to the context.
JAVASCRIPT
const changeColor = color => context.strokeStyle = color
You can check out a working version of it right here!