Fabric JS Unicode Issue - fabricjs

We are using Fabric JS (4.1.0) and noticed that special characters like ! or # are not pulling through to the text object in the canvas. They are simply showing as space characters but normal alphabet characters come through as expected.
I've collated the below script to grab the unicode of a string and return it back as a unicode string. Running the function below returns the exact unicode data we expect however, when passing the variable of the unicode string to it, the \u2702 text simply shows, however if I pass the same value in "hardcoded" like the commented out part it renders as expected.
Why is this happening and how can we fix it?
function unicodeEscape(str) {
return str.replace(/[\s\S]/g, function(character) {
var escape = character.charCodeAt().toString(16),
longhand = escape.length > 2;
longhand = true;
return '\\' + (longhand ? 'u' : 'x') + ('0000' + escape).slice(longhand ? -4 : -2);
});
}
canvas.clear();
var encodedVal = unicodeEscape('✂');
console.log(encodedVal);
text = new fabric.Text(encodedVal);
canvas.add(text);
// Function call that works perfectly and renders the element:
// text = new fabric.Text("\u2702");
// canvas.add(text);

Related

Insert commas into string number

I have this code, and I want to put commas.
I've seen many examples, but I dont now were put the code.
This is my AS3 code:
calccn.addEventListener(MouseEvent.CLICK,result1);
function result1(e:MouseEvent)
{
var vev: Number = (Number(vev.text));
var cn1: Number = (Number(3/100));
var result1f: Number = (Number(vev*cn1));
var round;
round=result1f.toFixed(0);
v3.text = String(round);
}
Example
If the result give me 1528000,32
I want that the result is 1.528.000 or 1 528 000
I didn't know (live and learn, eh), but there's actually a dedicated class: NumberFormatter.
If you want to do the thing on a regular basis, you might want a method to call:
// Implementation.
import flash.globalization.NumberFormatter;
// The default separator is comma.
function formattedNumber(value:Number, separator:String = ","):String
{
var NF:NumberFormatter;
NF = new NumberFormatter("en_US");
// Enforce the use of the given separator.
NF.groupingSeparator = separator;
// Ignore the fraction part.
NF.fractionalDigits = 0;
return NF.formatNumber(value);
}
// Usage.
//Format the given number with spaces for separator.
trace(formattedNumber(1528000.32, " ")); // 1 528 000
//Format the given number with the default separator.
trace(formattedNumber(1528000.32)); // 1,528,000
But if you want just a simple one-timer, and don't really care if it is commas or spaces as long as they present you may just condense in into a single expression:
calccn.addEventListener(MouseEvent.CLICK, result1);
function result1(e:MouseEvent):void
{
// Declaring variables with the same names as
// other entities is a generally bad idea.
var input:Number = Number(vev.text);
var cn1:Number = 3.0 / 100.0;
// Keep in mind that I used int() here as
// a simple tool to remove the fraction part.
v3.text = (new NumberFormatter("en_US")).formatNumber(int(input * cn1));
}

How to get the right values when I convert hex to ascii character

I'm trying to convert a hexa file to text, using javascript node js.
function hex_to_ascii(str1){
var hex = str1.toString();
var str = '';
for (var n = 0; n < hex.length; n += 2) {
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
}
return str;
}
I have a problem concening the extended ASCII charaters, so for example when I try to convert 93 I've get “ instead of ô and when I convert FF I've get ÿ instead of (nbsp) space.
I want to get the same extended charaters as this table: https://www.rapidtables.com/code/text/ascii-table.html
This problem is slightly more complex than it seems at first, since you need to specify an encoding when converting from extended ascii to a string. For example Windows-1252, ISO-8859-1 etc. Since you wish to use the linked table, I'm assuming you wish to use CP437 encoding.
To convert a buffer to string you need a module that will do this for you, converting from a buffer (in a given encoding) to string is not trivial unless the buffer is in a natively supported node.js encoding, e.g. UTF-8, ASCII (7-bit only!), Latin1 etc.
I would suggest using the iconv-lite package, this will convert many types of encoding. Once this is installed the code should look as follows (this takes each character from 0x00 to 0xFF and prints the encoded character):
const iconv = require('iconv-lite');
function hex_to_ascii(hexData, encoding) {
const buffer = Buffer.from(hexData, "hex");
return iconv.decode(buffer, encoding);
}
const testInputs = [...Array(256).keys()];
const encoding = "CP437";
console.log("Decimal\tHex\tCharacter")
for(let input of testInputs) {
console.log([input, input.toString(16), hex_to_ascii(input.toString(16), encoding)].join("\t"));
}

TextField.text is assigned with a multi-line string, but they're not equal right after the assignment

I have an Array of strings:
private var phrase:Array = ["You will be given a series of questions like this:\n2 + 2 =\n(click or press ENTER to continue)","You can use the Keyboard or Mouse\nto deliver the answer\n\"ENTER\" locks it in.\n(click or press ENTER to continue)","\nClick Here\n to start."];
I have a conditional later in the script to see if the phrase[0] is equal to the instructText.text, so I put a "test" directly after the assignment as below:
instructText.text = phrase[0];
if (instructText.text == phrase[0]) {
trace("phrase zero");
}
else {
trace("nottttttttt");
}
//OUTPUT: nottttttttt
I've tried various combinations of phrase[0] as String and String(phrase[0]), but haven't had any luck.
What am I missing?
Turns out that the text property of the TextField class converts the "Line Feed" characters (the "\n", ASCII code of 1010=A16) to the character of "Carriage Return" (the ASCII code of 1310=D16).
So, you need a LF to CR conversion (or vise-versa) to make a homogeneous comparison of what is stored in the property against what you have in the array element:
function replaceLFwithCR(s:String):String {
return s.replace(/\n/g, String.fromCharCode(13));
}
if (instructText.text == replaceCRwithLF(phrase[0])) {
trace("They are equal :)");
}
else {
trace("They are NOT equal :(");
}
// Output: They are equal :)
P.S. To get the code of a character, you may utilize the charCodeAt() method of the String class:
trace("\n".charCodeAt(0)); // 10

How to include emoticons in Swift string?

Here is a pretty good article that references iOS emoticons and their code. For example \ue008 for the small camera.
I tried this in my code :
var myText: String = "\ue008"
This is not accepted by Xcode. How to include it ?
If I understand what you are trying to achieve, then:
Press "ctrl + cmd + space" while in XCode. A sample usage of 'hearts' emoticon
cell.textLabel?.text = "❤️" + " \(liker) liked \(userBeingliked)'s photo"
That's from swift documentation:
let dollarSign = "\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496
You don't need the unicode constants at all. Just use the character viewer and type the character directly. 😝
let sparklingHeart = "💖"
1 Decoding the Unicode:
extension String {
var decodeEmoji: String{
let data = self.data(using: String.Encoding.utf8);
let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
if let str = decodedStr{
return str as String
}
return self
}
}
Usage
let decodedString = yourString.decodeEmoji
2 Encoding the Unicode:
extension String {
var encodeEmoji: String{
if let encodeStr = NSString(cString: self.cString(using: .nonLossyASCII)!, encoding: String.Encoding.utf8.rawValue){
return encodeStr as String
}
return self
}
}
Usage
let encodedString = yourString.encodeEmoji
You could insert the emoji directly using ⌘ ^ Space.
Or, based on Greg's answer:
var myText: String = "\u{e008}"
As Greg posted above, you can directly input the emoji into Swift using the OSx character viewer. The character viewer is disabled by default. Here is how to enable it:
Go to System Preferences > Language and Region > Keyboard Preferences > Keyboard then check Show Keyboard, Emoji, & Symbol Viewers in menu bar. Once checked you can open the character viewer from the top right menu bar next to your Wifi and Date/Time icons.
from your Hex "0x1F52D" to actual Emoji
let c = 0x1F602
next step would possibly getting an Uint32 from your Hex
let intEmoji = UnicodeScalar(c!).value
from this you can do something like
titleLabel.text = String(UnicodeScalar(intEmoji)!)
here you have a "😂"
it work with range of hexadecimal too
let emojiRanges = [
0x1F600...0x1F636,
0x1F645...0x1F64F,
0x1F910...0x1F91F,
0x1F30D...0x1F52D
]
for range in emojiRanges {
for i in range {
let c = UnicodeScalar(i)!.value
data.append(c)
}
}
to get multiple UInt32 from your Hex range for exemple
Chris Slowik's and Greg's answers are close.
The easiest answer is just to "rephrase" your String from this:
var myText: String = "\ue008"
To this:
var myText: String = "\u{008}"
The Unicodes found on the link you've attached are not wrong, as someone else claimed. You just need to rephrase it inside the String.
The important piece of code in your example above is the "008" part.
I've created a simple function to convert these kinds Unicode to their corresponding Emojis:
func convertHexToEmoji(_ u:Int) -> String {
return "\(UnicodeScalar(u)!)" }
To use:
let myText = convertHexToEmoji(008)
print(myText)
This took me a bit of time to figure out in MacOS 11, so I thought I would share.
If you prefer to input the unicode characters rather than pasting literal emojis, you can find out the unicode for the system emojis like this:
Focus/click into a text field (e.g. the search bar in your web browser).
Press ctrl+cmd+space or go to Edit->Emoji & Symbols in the menu bar.
Scroll up in the character viewer until you see the window expand icon in the upper right:
In the expanded Character Viewer window, press the upper left button and select Customize List....
Scroll down to Code Tables minimized list, expand the list, toggle on Unicode, and press Done (system changed this window to dark mode for whatever reason).
Now, click the different emojis and you should see the unicode underneath the image.
Then you inject it the unicode like this:
var myText: String = "\u{e008}"

Using loops to go through string and check char as a dict key

so I want to kind of build a "Decrypter", I have a dictionary with the keys being the symbol, and the value the respective value for the symbol, then I have this string that the code is suppose to look into, the translate will be saved in a other string, in this case called output. This is the way I did the loop part, but is not working:
var outputText = " "
for character in textForScan{
for key in gematriaToLetters{
if (gematriaToLetters.keys == textForScan[character]){
outputText.insert(gematriaToLetters.values, atIndex: outputText.endIndex)
}
}
}
You could also consider using map:
let outputText = "".join(map(textForScan) { gematriaToLetters[String($0)] ?? String($0) })
If you don't specify a specific letter in the dictionary it returns the current letter without "converting".
I think you are looking for something like this:
for aCharacter in textForScan {
let newChar = gematrialToLetters["\(aCharacter)"]
outputText += newChar
}
print(outputText)

Resources