Center.js is a HTML5 Canvas based library that allows you to create simple text based icons, avatars, logos, and more. The library assists with drawing simple shapes, centering text, and setting fonts and colors.
Centering text with HTML5 canvas using textAlign
and textBaseline
has different behavior across browsers and fonts. Center.js removes inconsistencies by manually centering text.
yarn install
yarn examples
The centerjs library takes a canvas object and some configuration.
centerjs({
canvas: document.getElementById("canvas"),
width: 64,
height: 64,
shape: "square",
fontColor: "#581845",
backgroundColor: "#DAF7A6",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
There are 3 shapes to choose from:
- square
- circle
- rounded
centerjs({
canvas: document.getElementById("square"),
width: 64,
height: 64,
shape: "square",
fontColor: "white",
backgroundColor: "#FFC300",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
centerjs({
canvas: document.getElementById("circle"),
width: 64,
height: 64,
shape: "circle",
fontColor: "white",
backgroundColor: "#FFC300",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
centerjs({
canvas: document.getElementById("rounded"),
width: 64,
height: 64,
shape: "rounded",
fontColor: "white",
backgroundColor: "#FFC300",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
The dimensions of the canvas can be controlled using the width
and height
attributes which are measured in pixels.
centerjs({
canvas: document.getElementById("square"),
width: 128,
height: 64,
shape: "square",
fontColor: "white",
backgroundColor: "#FF5733",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
centerjs({
canvas: document.getElementById("circle"),
width: 128,
height: 128,
shape: "circle",
fontColor: "white",
backgroundColor: "#FF5733",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
centerjs({
canvas: document.getElementById("rounded"),
width: 64,
height: 128,
shape: "rounded",
fontColor: "white",
backgroundColor: "#FF5733",
text: "C",
fontFamily: "Helvetica",
fontSize: 48
});
Center.js will work with standard fonts as well as Google Web Fonts. Feel free to use any Google Web Fonts you've loaded via <link>
tags. If you need to load Google Web Fonts dynamically then include the Web Font loader in your application as shown below.
<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.26/webfont.js"></script>
WebFont.load({
google: {
families: ["Aladin"]
},
active: function() {
centerjs({
canvas: document.getElementById("google-web-fonts-1"),
width: 256,
height: 128,
shape: "rounded",
fontColor: "white",
backgroundColor: "#C70039",
text: "canvas",
fontFamily: "Aladin",
fontSize: 80
});
}
});