HTML5 Canvas | Drawing Text With Circles | Part 01

Video Tutorial

Overview

After Learning the basics behind rendering basic shapes using canvas, it’s time to try to make crazy animations using circles and forming a text.

Drawing Circles

Now we need to use a fake text rendered in the background without being displayed which will allow us to get the position of each pixel under the text shape then render upon it a circle while leaving spaces between a circle and another.

So for That, we create another canvas and we render a white text on it

//Background Canvas
var bgCanvas = document.createElement('canvas');
bgCanvas.width = window.innerWidth;
bgCanvas.height = window.innerHeight;
//The Background Context 
var bgCtx = bgCanvas.getContext('2d');

var displayedText = "Nice!"; ///< change to your custom text 

//Text Rendering
bgCtx.beginPath();
bgCtx.font = "300px impact";
bgCtx.fontStyle = "#ffffff";
bgCtx.fillText(displayedText, 50, 275);
//But you won't see the text because the background canvas is not under the DOM, just a virtual Canvas!

Then we get the pixels position and we create a function for batching (pushing all the circles(object) positions), so we can loop through the data again and render all the circle to the screen using the exact position of each circle.

//Circles Array 
var circles = [];

function init() {
    for (height = 0; height < bgCanvas.height; height += densess) {
        for (width = 0; width < bgCanvas.width; width += densess) {
            //We get the PIXEL DATA
            pixel = imageData.data[(width + height * bgCanvas.width) * 4 - 1];
        }
    }
}

function drawCircle(x, y) {

    circles.push({
        gX: x, ///< Goal X
        gY: y, ///< Goal Y
        col: "yellow", ///< a custom color for all the circles 
    });
}

init();

//And Also Check for the Pixel Value and Render a Circle of true on the init function 
if (pixel == 255) {
   drawCircle(width, height); ///< we draw on each pixel 
}

and for rendering all the circle to the screen, just loop through the array

//Rendering the Ready Circles
function renderCircles(circles = {}) {
    //if (circles == {}) return false;
    //Loop al Circles
    for (var i = 0; i < circles.length; i++) {
        var circ = circles[i];
        //console.log(circ);
        ctx.beginPath();
        ctx.arc(circ.gX, circ.gY, circlRadius, 0, Math.PI * 2, false);
        ctx.fillStyle = circles[i].col;
        ctx.closePath();
        ctx.fill();

    }
}

renderCircles(circles);

As simple as that you should see a Set of yellow Circle forming your text, change the text Variable to whatever you like rather than “Nice!”

Check out the Video Tutorial for more Detailed Information.

What’s Next

So this was only for rendering a basic text shape using yellow circles, in the next tutorial or Part 02 we are going to animate the circles and we make the crazy effect of circles releasing and Back-In-Time Effect on space bar click, Stay Tuned!

No Comments Yet