Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teaches me how to (if you know one, please share).

Now, my question is how can I modify the colors of these different strokes?

self.context.clearRect( 0, 0, self.width, self.height );
        self.context.lineWidth = 10;
        self.context.fillStyle = "#000";
        self.context.strokeStyle = "#666";
        self.context.textAlign = "center";

You can find the code I found in the link below.

http://codepen.io/gabrieleromanato/pen/OVprOW

Answer №1

To change the color of elements on your page, comment out the line

self.context.strokeStyle = "#d30000";
. Then, assign an id to each element and set the desired color using
document.getElementById("given-id").getContext( "2d" ).strokeStyle = "#desired-color";
. See example below:

/* Modify the color of elements on a web page */
document.getElementById("csscan").getContext( "2d" ).strokeStyle = "#d30000";
document.getElementById("html5can").getContext( "2d" ).strokeStyle = "blue";
(function() {

var Progress = function( element ) {

this.context = element.getContext( "2d" );
this.refElement = element.parentNode;
this.loaded = 0;
this.start = 4.72;
this.width = this.context.canvas.width;
this.height = this.context.canvas.height;
this.total = parseInt( this.refElement.dataset.percent, 10 );
this.timer = null;

this.diff = 0;

this.init();
};

Progress.prototype = {
init: function() {
var self = this;
self.timer = setInterval(function() {
self.run();
}, 25);
},
run: function() {
var self = this;

self.diff = ( ( self.loaded / 100 ) * Math.PI * 2 * 10 ).toFixed( 2 );
self.context.clearRect( 0, 0, self.width, self.height );
self.context.lineWidth = 10;
self.context.fillStyle = "#000";
//self.context.strokeStyle = "#d30000";
self.context.textAlign = "center";

self.context.fillText( self.loaded + "%", self.width * .5, self.height * .5 + 2, self.width );
self.context.beginPath();
self.context.arc( 35, 35, 30, self.start, self.diff / 10 + self.start, false );
self.context.stroke();

if( self.loaded >= self.total ) {
clearInterval( self.timer );
}

self.loaded++;
}
};

var CircularSkillBar = function( elements ) {
this.bars = document.querySelectorAll( elements );
if( this.bars.length > 0 ) {
this.init();
}
};

CircularSkillBar.prototype = {
init: function() {
this.tick = 25;
this.progress();

},
progress: function() {
var self = this;
var index = 0;
var firstCanvas = self.bars[0].querySelector( "canvas" );
var firstProg = new Progress( firstCanvas );

var timer = setInterval(function() {
index++;

var canvas = self.bars[index].querySelector( "canvas" );
var prog = new Progress( canvas );

if( index == self.bars.length ) {
clearInterval( timer );
} 

}, self.tick * 100);

}
};

document.addEventListener( "DOMContentLoaded", function() {
var circularBars = new CircularSkillBar( "#bars .bar" );
});

})();
#bars {
margin: 2em auto;
max-width: 960px;
overflow: hidden;
}

.bar {
float: left;
width: 20%;
text-align: center;
}

.bar h3 {
font-size: 1.4em;
font-weight: normal;
margin: 0;
text-transform: uppercase;
}

.bar-circle {
display: block;
margin: 0.7em auto;
}
<div id="bars">
<div class="bar" data-percent="100" >
<h3>CSS</h3>
<canvas class="bar-circle" width="70" height="70" id="csscan"></canvas>
</div>
<div class="bar" data-percent="100">
<h3>HTML5</h3>
<canvas class="bar-circle" width="70" height="70" id="html5can"></canvas>
</div>
<div class="bar" data-percent="100">
<h3>JavaScript</h3>
<canvas class="bar-circle" width="70" height="70"></canvas>
</div>
<div class="bar" data-percent="100">
<h3>PHP</h3>
<canvas class="bar-circle" width="70" height="70"></canvas>
</div>
<div class="bar" data-percent="80">
<h3>Server</h3>
<canvas class="bar-circle" width="70" height="70"></canvas>
</div>
</div>

Answer №2

If you want to initialize the function, you simply need to provide some arguments when calling the init method.

I made changes to your Pen

init: function(fillStyle, strokeStyle) {
        var self = this;
        self.context.fillStyle = fillStyle,
        self.context.strokeStyle = strokeStyle,
        self.timer = setInterval(function() {
        self.run(); 
    }, 25);
}

Now, when calling the init function, make sure to pass in 2 parameters for strokeStyle and fillStyle.

this.init('#0F0', '#F00');

Update: I have made further adjustments to the pen by incorporating random colors for a more visually appealing effect.

Answer №3

To manipulate the color attribute, you can follow a similar approach as with the width and height attributes. Simply store the color value within an attribute on the canvas element, then retrieve that value within the progress function.

Explore this example on CodePen

<canvas class="bar-circle" color="blue"  width="70" height="70"></canvas>

this.color = element.getAttribute('color') || "#d30000"; //default

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

react-native-track-player failing to play song requested from Express server

I set up an expressjs server with a 'songs' route that serves .mp3 files. Here is the code for the Songs Route: import express from "express" const path = require("path") const router = express.Router() ... router.get(" ...

How can I customize the color of Chrome's default date and time picker to a different shade of blue?

Is there a way to customize the color of the blue buttons, text, and date indicator in the native datetime picker for Chrome using CSS? https://i.stack.imgur.com/eZSaE.png ...

Experiencing Issues with File Downloading on Express Server with Axios and Js-File-Download Library

I developed a feature on my express server that allows users to download a file easily. app.post("/download", (req, res) => { let file_name = req.body.name; res.download(path.join(__dirname, `files/${file_name}.mp3`), (err) => { ...

Positioning the video tag bar in HTML is a crucial element to

**Take a look at what I'm discussing here(http://jsfiddle.net/VpLyR/). I'm dealing with a simple code that includes a video tag (html) and a menu bar with a fixed position. The issue arises when I scroll down to the point where both the menu bar ...

Attempting to replace the checkbox image resulted in no changes

<?php require 'includes/configs.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php $site_name ?></titl ...

A guide to dynamically rendering pages in Next.js

Currently, I am working on rendering a webpage on the frontend by fetching data from the database. The route for a specific webpage is hard coded at the moment, but I am looking to make it dynamic as there are multiple webpages in the database. I also want ...

Unable to upload photo using Ajax request

I am in the process of trying to utilize Ajax to upload an image, so that it can be posted after the submit button is clicked. Here is the flow: User uploads image -> Ajax call is made to upload photo User clicks submit -> Post is shown to the user ...

Uploading and downloading files to a localhost server using PHP

Currently facing an issue where I have successfully uploaded a Picture, PPTX, and PDF file to the database server. However, when viewing them in the browser: The Picture displays normally. However, The PDF file automatically downloads upon trying to view ...

Styling a div element in CSS so that it adjusts its size to fit its

How can I make a div element adjust to its content and also break the line so that the next element appears below it? I attempted setting the display property to inline-block, but then the div no longer breaks the line... Normally, it breaks the line, but ...

How to customize a dropdown menu with the size property?

Can anyone help me with styling a select box that uses the size attribute? Most tutorials only cover single-item select boxes. Has anyone dealt with styling select boxes with the size attribute before? Here's an example of what I'm trying to acc ...

Learn how to run javascript code using Nodejs child_process and Meteor

Is it possible to use the child_process module to execute Meteor server-side code instead of just Linux commands? I am interested in using spawn to create a separate process for running my loop. The loop involves logging a message every minute. myLoop(){ ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...

Chaining promises: The benefits of attaching an error handler during Promise creation versus appending it to a variable containing a promise

function generatePromise() { return new Promise((resolve, reject) => { setTimeout(reject, 2000, new Error('fail')); }); } const promise1 = generatePromise(); promise1.catch(() => { // Do nothing }); promise1 .then( ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Change PHP code to a JSON file format

I am currently learning Laravel and my current focus is on how to send a JSON file from the back end to the front-end. I intend to utilize this JSON data to generate a graph. Within my model, I have created a function that retrieves values and timestamps ...

Superior method to ensure the child element's border overlaps with that of the parent

I am currently working on a project that requires a unique CSS effect: Let me explain exactly what I am trying to achieve: The main element (referred to as the title) has padding and a 2px bottom border. Inside this, there is a child element (known as ti ...

Strange flickering/visualization issue experienced with transparent MeshPhongMaterial in Three.JS

In my scene, I have a Mesh called cylinder: const cylinder = new Mesh( new CylinderGeometry(2, 2, 1, 32), new MeshPhongMaterial({ color: color, shininess: 32, opacity: 0, transparent: true, specular: 0xffff82, }), ); I made the ...

What is the most effective method to implement a toggle function using only JavaScript, without any reliance on jQuery?

Recently, I had a navigation bar in the form of an unordered list (ul) with multiple list items (li), and the last li element was labeled 'more' which had its own sub-menu in the form of another ul. To toggle this sub-menu between visible and hid ...

Tips for preventing browsers from losing style information stored in inputs

My custom input field has unique CSS styles applied to it, but unfortunately, when the browser auto-fills the information in those fields, the styles get reset. ...

The Angular module instantiation failed with the error message: "[$injector:modulerr] Failed to

Struggling with setting up basic AngularJS functionality for a project, especially when trying to include angular-route. Both components are version 1.4.8. My approach involves using gulp-require to concatenate my JS files. Here is my main javascript file: ...