JSFiddle - React, Tailwind, and code Playground
by adil_invideo
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.3.3/pixi.min.js"></script>
JavaScript
class RichTextChar extends PIXI.Sprite {
constructor(content, band) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const texture = PIXI.Texture.from(canvas);
super(texture);
this.context = context;
this.band = band;
this.content = content;
// console.log(this);
this.dirty = true;
}
/**
* Renders the text into {@code this.canvas}.
*/
renderText() {
const canvas = this.context.canvas;
const ctx = this.context;
ctx.clearRect(0, 0, canvas.width, canvas.height);
let width = 0;
if (this.content.metric) width = this.content.metric.width;
let height = 0;
if (this.content.metric) height = this.content.metric.height;
canvas.width = width * 2;
canvas.height = height * 2;
this.texture._frame.width = canvas.width;
this.texture._frame.height = canvas.height;
this.texture.baseTexture.setRealSize(canvas.width, canvas.height, 1);
// this.context.strokeRect(0, 0, width, height);
const command = {
...this.content
};
if (command.font) {
ctx.font = command.font;
}
if (command.fillStyle) {
ctx.fillStyle = command.fillStyle;
}
if (command.char === '\n') {
return;
}
ctx.fillText(command.char, 0, height);
}
update() {
if (this.dirty) {
this.renderText();
this.dirty = false;
}
}
render(renderer) {
this.update();
super.render(renderer);
}
}
class RichText extends PIXI.Container {
constructor(content, band) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const texture = PIXI.Texture.from(canvas);
super(texture);
this.context = context;
this.content = content;
this.chars = [];
this.words = [];
this.lines = [];
this.band = band;
this.layout = {
diffs: [],
width: 0,
height: 0
};
this.lineDimens = {
widths: [],
...