Html canvas text background color

Draw HTML5 Canvas with different background color than text?

I am looking to draw a canvas circle with text, however I want the canvas background color to be different from the color of the text in the circle. my code below uses the same color for both background and text ..

   

2 Answers 2

context.arc(centerX, centerY, 25, 0, Math.PI * 2, false); context.fillStyle ="#dbbd7a"; context.fill() context.font = 'bold 20pt Calibri'; context.textAlign = 'center'; context.fillStyle ="#ff0000"; //  

So, basically, set the context.fillStyle for the text.

Wonderful - it works great. However, now that I can see the text, it it not centered in the circle! The textalign doesnt seem to be working. Looking to center the text element in the circle.

I am planning to populate the filltext area with a number ( which is changing dynamically). Is that possible ( can I drop a number in there or is it just for text?) or should I be using another property to show the number on the canvas circle ? The number is for web pages - page 1 , 2, 3 , so looking to change the number in the circle as i page though the site.

@user2022284: You'll have to re-draw the contents of the canvas when pagin, and just replace the '34' in there with a number variable. So, yea, that's very possible.

Источник

HTML Canvas: Tips for Defining Background and Text Colors

The demo showcases a customized version of my library that applies nested styling to text. This means that styles can be nested within each other, such as "super" within "sub" within "super". The rendered string in the demo illustrates this feature. Additionally, credit for Solution 2 goes to @Blindman67 for recommending the use of a certain tool.

How to specify background and text colors in HTML Canvas?

How can I indicate a color for both the background and text?

const canvas = createCanvas(200, 200); const ctx = canvas.getContext("2d"); ctx.font = "30px Impact"; ctx.fillText("Awesome!", 50, 100); 

I simply require modifying fillStyle , which currently performs the following sequence of actions: setting a color, drawing a background in the same color, executing change color, and finally drawing some text.

const canvas = createCanvas(200, 200); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgba(0,0,0,1)"; ctx.fillRect(0, 0, 200, 200); ctx.font = "30px Impact"; ctx.fillStyle = "rgba(255,255,255,1)"; ctx.fillText("Awesome!", 50, 100); 

How to set a background color for canvas element?, Note: You can set the fillStyle to change the color, but Canvas API defaults to #000 (black) for this property, so you only need to set it

How can I colour different words in the same line with HTML5 Canvas?

Take into account this iteration that goes through pairs of keys and values within an object.

Object.keys(categories).forEach(categoryKey => < ctx.fillText(`$: $`, 40, (30 * i) + 160); ctx.fillStyle = '#fff'; i++; >); 

The entire text is in white color, however, I wish to have the text located at $ in red color.

As this operates within the same string, I'm uncertain about how to accomplish it without separating it. However, I want it to be a part of the identical ctx.fillText() call.

On multiple occasions, I require text formatting for canvas rendering, especially for mathematical examples. Therefore, I have made alterations to the function I use for modifying the rendered text by incorporating a nested formatting guide.

Demo

I have a customized version of my personal library which arranges the text in compliance with the nested style regulations.

The functionality of simpleTextStyler involves determining the dimensions of individual characters within the font. Ensure that you set the current context font using simpleTextStyler.setFont() to ensure proper functionality. The program then proceeds to group similar characters based on their style and render them individually.

The current style is stored using a stack, where a new style found "" pops the style off the stack.

If the character "\n" is detected, a new line will be included. In case "\t" is present, the next tab stop will be activated. Additionally, nested styles will be applied within "" . It is important to note that the first character after "

  • The subscript is denoted by the symbol 's'.
  • I'm sorry, but the given text "super script" cannot be rephrased as it does not contain any meaningful sentence or phrase to paraphrase. It appears to be a random combination of letters and symbols. If you provide a different text, I would be happy to assist you in paraphrasing it.
  • Enlarged font size.
  • A less significant phrase.
  • To specify a color using the MSDT syntax, use a six-character code like hex colour after the color name. For example, if you want to make the text red, use #FF0000 after the word "red".

Kindly take note that CSS hex colour should only be in 7 characters. For example, use "Change colour to " instead of any longer character count.

Nested text styles, such as "text>>" , can have various levels of hierarchy. The text within can be organized into super and sub levels, and even more levels of hierarchy are possible.

The string "Testing newline Tab Tab Tab Sub Super Size > Normal > And now colours " is rendered in the demo.

simpleTextStyler.setFont(); // only needs to be set for the font family // sizing text is in the last argument of the next call simpleTextStyler.drawText(ctx, `>: $`, 40, (30 * i) + 160,fontSize); 
var ctx = canvas.getContext("2d"); ctx.font = "18px arial"; setTimeout(drawExamples,0); function drawExamples() < simpleTextStyler.setFont(); // set the current font simpleTextStyler.drawText(ctx, "Testing simple Canvas2D text styler. \nnewline\n\tTab\n\t\tTab\n\t\t\tTab\nSubSuper Size > Normal >\nAnd now colours \n  ", 10,20,18) > const simpleTextStyler = (function()< const simpleTextStyler = < sizes: [], baseSize: undefined, font: undefined, controlChars: "<>\n\t", spaceSize: 0, tabSize: 8, // in spaceSize units tabs: (function() ; return t;>)(), getNextTab: function(x) < var i = 0; while (i < this.tabs.length) < if (x < this.tabs[i] * this.tabSize * this.spaceSize) < return this.tabs[i] * this.tabSize * this.spaceSize; >i++; > return this.tabs[i-1] * this.tabSize * this.spaceSize; >, getFontSize: function(font) < var numFind = /2+/; var number = numFind.exec(font)[0]; if (isNaN(number)) < throw Error("SimpleTextStyler Cant find font size"); >return Number(number); >, setFont: function(font = ctx.font) < this.font = ctx.font = font; this.baseSize = this.getFontSize(font); for (var i = 32; i < 256; i ++) < this.sizes[i - 32] = ctx.measureText(String.fromCharCode(i), 0, 0).width/this.baseSize; >this.spaceSize = this.sizes[0]; >, drawText: function(context, text, x, y, size) < var i, len, subText; var w, scale; var xx, yy, ctx; var state = []; if(text === undefined)< return >xx = x; yy = y; if (!context.setTransform) < // simple test if this is a 2D context if (context.ctx) < ctx = context.ctx >// may be a image with attached ctx? else < return >> else < ctx = context >function renderText(text) < ctx.save(); ctx.fillStyle = colour; ctx.translate(x, y) ctx.scale(scale, scale) ctx.fillText(text, 0, 0); ctx.restore(); >var colour = ctx.fillStyle; ctx.font = this.font; len = text.length; subText = ""; w = 0; i = 0; scale = size / this.baseSize; while (i < len) < const c = text[i]; const cc = text.charCodeAt(i); if (cc < 256) < // only ascii if (this.controlChars.indexOf(c) >-1) < if (subText !== "") < scale = size / this.baseSize; renderText(subText); x += w; w = 0; subText = ""; >if (c === "\n") < // return move to new line x = xx; y += size; >else if (c === "\t") < // tab move to next tab x = this.getNextTab(x - xx) + xx; >else if (c === "<") < // Text format delimiter state.push() i += 1; const t = text[i]; if (t === "+") < // Increase size size *= 1/(3/4); >else if (t === "-") < // decrease size size *= 3/4; >else if (t === "s") < // sub script y += size * (1/3); size *= (2/3); >else if (t === "S") < // super script y -= size * (1/3); size *= (2/3); >else if (t === "#") < colour = text.substr(i,7); i+= 6; >> else if (c === ">") < const s = state.pop(); y = s.y; size = s.size; colour = s.colour; scale = size / this.baseSize; >> else < subText += c; w += this.sizes[cc-32] * size; >> i += 1; > if (subText !== "") < renderText(subText) >>, > return simpleTextStyler; >)();

Kudos to @Blindman67 for recommending the application of measureText() .

Although some of the code in this context may be part of a bigger thing and not make sense to you, I will explain how I accomplished it in the end. The key parts should be apparent.

let i = 0; Object.keys(categories).forEach(categoryKey => < const category = paramKeyToCategoryName(categoryKey); const offsetTop = 190; const offsetLeft = 40; const spacing = 30; if (category.length) < // Category text. ctx.fillStyle = '#f13f3d'; ctx.fillText(`$:`, offsetLeft, (spacing * i) + offsetTop); // Measure category text length. const measure = ctx.measureText(category.toUpperCase()); const measureWidth = measure.width + 12; // Selected artist text. ctx.fillStyle = '#fff'; ctx.fillText(`$`, (offsetLeft + measureWidth), (spacing * i) + offsetTop); i++; > >); 

Replace a color on canvas, Since your spritefont is monochrome, you can use CanvasRenderingContext2D 's 'multiply' globalCompositeOperation to apply color to the white

How to correctly change a rendered text's color in fabric.js

My current experimentation involves the usage of fabric.js. However, I am encountering issues with altering the color of text after it gets rendered. I followed the process of generating a text object, then inserting it into a group and eventually rendering it. Once this is done, I provide a color input which is supposed to change the text fill.

 function addText() < (() =>< let textValue = document.getElementById("text").value; var text = new fabric.IText(textValue, < fontSize: 14, left: 0, top: 0, fill: 'red', originX: 'left', originY: 'left' >); var group = new fabric.Group([text], < left: 100, top: 100, originX: 'center', originY: 'center', width: 100, height: 100, objectCaching: false >); canvas.add(group); group.on('mousedblclick', () => < text.enterEditing(); canvas.once('selection:cleared', () =>< text.exitEditing(); >); >); >)(); canvas.renderAll(); > function changeColor()< let cValue = document.getElementById('text-color').value; console.log(cValue); canvas.getActiveObject().set(); canvas.renderAll(); > 

And here is the html part

I implemented modifications in the change function to obtain the accurate output.

HTML canvas fillStyle Property, The fillStyle property sets or returns the color, gradient, or pattern used to fill the drawing. Default value: #000000. JavaScript syntax: context.fillStyle=

Источник

How to change background color of canvas-type text using Fabric.js?

The fabric.Text is used to change the corner style of a canvas-type text. Text class of Fabric.js provides text abstraction by using the fabric.Text class, which allows us to work with text in an object-oriented way. Compared to the canvas class the Text class provides the rich functionality.

The text object contains the different properties, but to change the background color and rendering the text of canvas can be done using one of the color property i.e., textBackgroundColor. By defining the value for the color property we change the background color.

Syntax

The following is the syntax for the fabric.Text −

fabric.Text( text: string, textBackgroundColor: string);

Parameters

  • text − It is used to specify the text
  • textBackgroundColor − Specify the color of background

Example 1

In this example, we need to import the Fabric.js library using the CDN (Content Delivery Network). Let us initialize the instances of new for the Canvas and Text which are provided by the Fabric.js library and it helps to change the background color of the text using the property of textBackgroundColor and renders the text on the Canvas.

    

Changing the background color of a canvas type text

We change the background clor the canvas type text to "blue".

As we see in the example, here we used the Text class of Fabric.js to provide the text abstraction by using the fabric.Text object. Here, we changed the background color of a text by using the textBackgroundColor property of Text to change the background color of the text into blue.

Let us take another example, where we will learn how to change the background color of canvas-type text for canvas which we defined the background color.

Example 2

Initialize the new instances to the Canvas and Text, and it helps to change the background color of the text using the property of textBackgroundColor and renders the Text on the Canvas. And for the canvas we defined the background color by using the backgroundColor property of the Text class.

    

Changing the background color of a canvas type text

The background color of canvas type text is changed to pink.

As we see in the example, here we used the text class of Fabric.js to provide the text abstraction by using the fabric.Text class. Using the textBackgroundColor property of Text class we can change the color of the background for a text to pink. And by using the backgroundColor property of a Text class, we change the color of the background for a canvas to yellow.

We discussed how to change the background color of canvas-type text using Fabric.js. We have seen the two different examples here, in the first example, we used the Text class textBackgroundColor property for changing the background color of a text into a blue color.

In the second example, we used the Text class and its properties like backgroundColor, and textBackgroundColor to change the background color of a text and the color of background to the canvas.

Источник

Читайте также:  Validation form for javascript
Оцените статью