In Font Awesome 4x I managed to set the cursor as an icon by changing it into a base-64 image url. Now in Font Awesome 5 it does not work any more.
I've found this solution, but it's not working here.
This is what I've tried.
var canvas = document.createElement("canvas");
canvas.width = 20;
canvas.height = 20;
var ctx = canvas.getContext("2d");
document.fonts.ready.then(function() {
ctx.font = "400 20px Font Awesome 5 Pro";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
setTimeout(function() {
ctx.fillText("\uf2ed", 10, 10)
var dataURL = canvas.toDataURL('image/png')
$('#foo').css('cursor', 'url(' + dataURL + '), auto');
}, 200)
})
All I get is a black square 20x20
Is there anyone who knows how to get it done?
see the below example ...
var hex = 0xF25A;
var unicode = String.fromCharCode(parseInt(hex, 16));
var canvas = document.getElementById("cache");
canvas.width = 64; canvas.height = 64;
var context = canvas.getContext("2d");
context.font = '900 32px "Font Awesome 5 Free"';
context.fillText(unicode, canvas.width/2, canvas.width/2);
document.fonts.ready.then(function() {
$('body').css('cursor', 'url(' + canvas.toDataURL('image/png') + '), auto');
});
html, body {height: 100%; width:100%; margin:0; padding: 0;}
canvas#cache {display: none;}
<link rel="stylesheet" href="//use.fontawesome.com/releases/v5.2.0/css/solid.css" integrity="sha384-wnAC7ln+XN0UKdcPvJvtqIH3jOjs9pnKnq9qX68ImXvOGz2JuFoEiCjT8jyZQX2z" crossorigin="anonymous">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="cache"/>
This is an old question, but I was successful using jquery.awesomecursor, and this JS:
$('body').awesomeCursor('cut', {color: '#3097d1',
font: {cssClass: 'far fa-%s',
family:'"Font Awesome 5 Pro"'
}
});
The key things here were:
. The cssClass for FontAwesome 5 ("regular" icons are 'far fa-X', not 'fa fa-X' as they were in prior versions)
. The way "family" is specified - I needed the inner set of quotes to make it work.
FWIW, I'm using this with WebPack so I needed to make sure faCut was loaded from "#fortawesome/pro-regular-svg-icons"; You can read more about this here.
Related
I want to change the font color based on the color of the image. The font color must be black or white, but it should change proportionally to the color of the image as it does in the code below.
So, I have this js function that if you move the mouse it changes the background color and consequently also the text (in the snippet move the pointer under the background). Obviously the part where you move the mouse to change color doesn't interest me, it's just a test. Is there a way to apply the function to my personal div?
In simple terms I want the color of the text to change based on my background and not if you move the mouse. Sorry for the poor explanation, I'm relatively new here, trying to learn how to exercise this function. Currently I don't know how to do it, I appreciate any answer, thanks.
function getTextColor(rgba){
rgba = rgba.match(/\d+/g);
if((rgba[0]*0.299)+(rgba[1]*0.587)+(rgba[2]*0.114)>186) {
return 'black';
} else {
return 'white';
}
}
var div = document.createElement('div');
div.style.height = '100vh';
document.body.appendChild(div);
div.addEventListener('mousemove', (event)=>{
var x = event.clientX;
var y = event.clientY;
div.textContent = `${x} , ${y}`;
div.style.backgroundColor = `rgba(${x},${y},100,100)`;
div.style.color = getTextColor(div.style.backgroundColor);
});
.background {
height: 100vh;
background: url("https://i.pinimg.com/originals/bc/a3/2d/bca32d5cdfabeaeb4faeb12bff160524.jpg");
}
<div class="background">Background example</div>
Explanation
Here is an example showing how to get the average using a canvas rendered to a 1x1-px scale. From there we set the header background and then apply a light or dark class based on the luminance of the aforementioned average.
Notes
Note 1:
There is some extra code to allow for easier visualization, this is commented and can be removed.
Note 2: The below code is not guaranteed to run on all browsers. Please see this thread for more specifics.
Note 3: This code only works with local images and CORS-enabled image URLs due to it's reliance on canvas.drawImage. Please see this for more information.
Example 1:
this example shows the functionality. It uses two image URLs in the JS to toggle between.
/*
THE TOGGLE ACTION
*/
/* The urls for toggling between */
const urlLight = 'https://images.unsplash.com/photo-1484503793037-5c9644d6a80a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=930&q=80';
const urlDark = 'https://images.unsplash.com/photo-1517999144091-3d9dca6d1e43?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=627&q=80';
let currentUrl = urlLight;
const toggle = document.getElementById('toggle');
toggle.addEventListener("click", function() {
if (currentUrl === urlLight) {
currentUrl = urlDark;
} else {
currentUrl = urlLight;
}
getImageBrightness(currentUrl, function(brightness) {
const header = document.getElementById("header");
header.style.backgroundImage = `url(${currentUrl}`;
header.classList.remove("dark");
header.classList.remove("light");
console.log(brightness);
if (brightness > 225 / 2) {
header.classList.toggle("dark");
} else {
header.classList.toggle("light");
}
});
});
/*
Important get brightness code
*/
function getImageBrightness(imageSrc, callback) {
var img = document.createElement("img");
img.src = imageSrc;
img.style.display = "none";
img.crossOrigin = "anonymous";
document.body.appendChild(img);
var colorSum = 0;
img.onload = function() {
// create canvas
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
var r, g, b, avg;
for (var x = 0, len = data.length; x < len; x += 4) {
r = data[x];
g = data[x + 1];
b = data[x + 2];
avg = Math.floor((r + g + b) / 3);
colorSum += avg;
}
var brightness = Math.floor(colorSum / (this.width * this.height));
callback(brightness);
}
}
getImageBrightness(currentUrl, function(brightness) {
const header = document.getElementById("header");
header.style.backgroundImage = `url(${currentUrl}`;
header.classList.remove("dark");
header.classList.remove("light");
if (brightness > 225 / 2) {
header.classList.toggle("dark");
} else {
header.classList.toggle("light");
}
});
.dark {
color: black;
}
.light {
color: white;
}
* {
text-align: center;
}
#header {
padding: 2rem 0;
font-size: 4rem;
background-size: cover;
margin-bottom: 1rem;
background-position: center center;
}
<div id="header">
Header
</div>
<button id='toggle'>
Toggle Background
</button>
Example 2:
This example directly answers the question by retrieving the background image of the current div and running the function using said image.
/*
Important get brightness code
*/
function getImageBrightness(imageSrc, callback) {
var img = document.createElement("img");
img.src = imageSrc;
img.style.display = "none";
img.crossOrigin = "anonymous";
document.body.appendChild(img);
var colorSum = 0;
img.onload = function() {
// create canvas
var canvas = document.createElement("canvas");
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
var r, g, b, avg;
for (var x = 0, len = data.length; x < len; x += 4) {
r = data[x];
g = data[x + 1];
b = data[x + 2];
avg = Math.floor((r + g + b) / 3);
colorSum += avg;
}
var brightness = Math.floor(colorSum / (this.width * this.height));
callback(brightness);
}
}
/* The element we wish to work on */
const header = document.getElementById("header");
/* To get the background image. Get style and then background image with a slice to remove quotes */
var imageElement = document.getElementById('header'),
style = imageElement.currentStyle || window.getComputedStyle(imageElement, false),
backgroundImage = style.backgroundImage.slice(4, -1).replace(/"/g, "");
getImageBrightness(backgroundImage, function(brightness) {
/* Remove dark and light classes from the element */
header.classList.remove("dark");
header.classList.remove("light");
/* check brightness and apply correct style */
/* Please modify the below brightness comparison statement to adjust to your needs */
if (brightness > 225 / 2) {
header.classList.toggle("dark");
} else {
header.classList.toggle("light");
}
});
.dark {
color: black;
}
.light {
color: white;
}
* {
text-align: center;
}
#header {
padding: 2rem 0;
font-size: 4rem;
background-size: cover;
margin-bottom: 1rem;
background-position: center center;
background-image: url('https://images.unsplash.com/photo-1530128118208-89f6ce02b37b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80')
}
<div id="header">
<h1>
Header
</h1>
</div>
I have seen in a couple of cases of converting text into images but nobody mention that if a text is too long i-e more then 1000 words how can I display them in image with using a font size of 15px
my HTML code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
</head>
<body>
<div id="the_text"></div>
<button id="show_img_btn">Convert to Image</button>
<div id="show_img_here"></div>
</body>
my Script code
window.onload=function(){
$("#show_img_btn").on("click", function () {
var canvas = document.createElement("canvas");
canvas.width = 620;
canvas.height = 80;
var ctx = canvas.getContext('2d');
ctx.font = "30px Arial";
var text = $("#the_text").text();
ctx.fillText(text,10,50);
var img = document.createElement("img");
img.src=canvas.toDataURL();
$("#show_img_here").append(img);
//$("body").append(canvas);
});
};
My question is if I convert this image it will converted into one line help me how can i convert the whole text into image and set the height and width.
Create a dummy element and apply same style props, append to dom and get the with of it. based on that you can split the text. Helpful snippet given below.
// JS:
function getDimen(text) {
var div = document.getElementById("dummy");
div.innerHTML = text
var h = (div.clientHeight + 1) + "px";
var w = (div.clientWidth + 1) + "px"
return({ h, w })
}
console.log(getDimen("some text hi a a s a a s as a s as a s as a s as a s"))
// HTML
<div id="dummy"></div>
// CSS:
#dummy {
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap;
}
I tried to figure it out looking at the source code but I couldn't figure it out.
I would like to know how to make a dynamic favicon with a count like Gmail does.
Any idea on how to do this?
You can make an image with the canvas element, and then just replace the current favicon. Check out the following link for a good explanation on it.
Reference
Code is from the above reference.
Markup
<link id="favicon" rel="icon" type="image/png" href="image.png" />
JS
(function () {
var canvas = document.createElement('canvas'),
ctx,
img = document.createElement('img'),
link = document.getElementById('favicon').cloneNode(true),
day = (new Date).getDate() + '';
if (canvas.getContext) {
canvas.height = canvas.width = 16; // set the size
ctx = canvas.getContext('2d');
img.onload = function () { // once the image has loaded
ctx.drawImage(this, 0, 0);
ctx.font = 'bold 10px "helvetica", sans-serif';
ctx.fillStyle = '#F0EEDD';
if (day.length == 1) day = '0' + day;
ctx.fillText(day, 2, 12);
link.href = canvas.toDataURL('image/png');
document.body.appendChild(link);
};
img.src = 'image.png';
}
})();
Edit
Must have an image set as well.
I'm trying to draw text onto a flag using a simple script. It works fine except for the Font not being loaded.
I've tried to load the font locally and from the web, but both don't work on my server.
However the code runs fine on w3 schools tryit editor
I think it has to do with the font not being loaded correctly or too late. What is the best way to make sure the font is loaded correctly?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">
<style>body { font-family: Ubuntu, sans-serif; }</style>
</head>
<body>
<canvas style="border-radius: 100px;" id="myCanvas" width="200" height="200">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var size = 200
var textSize=size * 0.55;
var countryCode = "nl";
var text = "123";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
img.onload = function(){
ctx.drawImage(img,-1,-1,size,size); // removes the 1px border the flags sometimes have
ctx.font = textSize+"px Ubuntu";
ctx.textAlign="center";
ctx.fillStyle = "#260C4D";
ctx.fillText(text,size/2,size/2 + textSize / 2.85);
};
img.src = "http://www.geonames.org/flags/x/"+countryCode+".gif";
</script>
</body>
</html>
I'm really tempted to vote to close as duplicate to this Q/A, but since you're in a particular case, I'll still post this answer, which may not be the best.
You are loading your font with a <link> element, so one way is to use its onload event handler.
The problem with this approach is that the font may be cached, and the load event may have fired before it reaches your script declarations.
So you could use the href +'&'+ new Date().getTime() trick to make a new request to the server, or you can remove the <link> from the DOM and reappend it. This way, its load event should fire again even if the cached version is used.
(Note that I only tested it on latest FF and Chrome, so it may not work in other browsers).
var link = document.querySelector('link');
link.onload = function() {
log.textContent = 'loading image...';
var size = 200
var textSize = size * 0.55;
var countryCode = "nl";
var text = "123";
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
img.onload = function() {
log.textContent='';
ctx.drawImage(img, -1, -1, size, size); // removes the 1px border the flags sometimes have
ctx.font = textSize + "px Ubuntu";
ctx.textAlign = "center";
ctx.fillStyle = "#260C4D";
ctx.fillText(text, size / 2, size / 2 + textSize / 2.85);
};
img.src = "http://lorempixel.com/200/200";
}
// in case it's in the cache, it seems we have to remove it from the DOM and reinsert it
link.parentNode.removeChild(link);
document.head.appendChild(link)
body {
font-family: Ubuntu, sans-serif;
}
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin">
<p id="log">loading font..</p>
<canvas style="border-radius: 100px;" id="myCanvas" width="200" height="200"></canvas>
I need to get the color of any pixel my mousepointer is currently hovering.
I found several solutions for canvas elements, but none for a background image defined in CSS for a element.
How can I achieve this?
Combining the answers from Get a CSS value with JavaScript and How to get a pixel's x,y coordinate color from an image?, I was able to simulate what you are looking for: JSFiddle
<html>
<head>
<style type="text/css">
#test {
background-image: url('http://jsfiddle.net/img/logo.png');
background-color: blue;
background-repeat: no-repeat;
height: 30px;
width: 100%;
}
#hidden {
display: none;
}
</style>
<script type="text/javascript">
var div = document.getElementById("test");
var style = window.getComputedStyle(div);
div.onmousemove = function(e) {
var path = style.getPropertyValue('background-image');
path = path.substring(4, path.length-1);
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = img.width;
canvas.height = img.height;
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
var pixelData = canvas.getContext('2d').getImageData(event.offsetX, event.offsetY, 1, 1).data;
var values = document.getElementById("values");
values.innerHTML = 'R: ' + pixelData[0] + '<br>G: ' + pixelData[1] + '<br>B: ' + pixelData[2] + '<br>A: ' + pixelData[3];
};
</script>
</head>
<body>
<div id="test"></div>
<div id="hidden">
<img id="i1" src="" />
<canvas id="c1"></canvas>
</div>
<div id="values"></div>
</body>
</html>
I retrieved the computed style (var style = window.getComputedStyle(div);) outside of the mouse move function for performance reasons, but if the background image is going to change dynamically, then it may need to be moved into the function.
There are some possible browser constraints for using getComputedStyle.
SCALING
You could try editing the code to adjust for the scale:
var h = parseInt(style.getPropertyValue("width")),
w = parseInt(style.getPropertyValue("height"));
var img = document.getElementById("i1");
img.src = path;
var canvas = document.getElementById("c1");
canvas.width = h;
canvas.height = w;
canvas.getContext('2d').drawImage(img, 0, 0, w, h);
This also includes a change to the CSS: JSFiddle