gpt4 book ai didi

javascript - Canvas 上一篇文本的不同格式?

转载 作者:行者123 更新时间:2023-12-03 02:40:37 26 4
gpt4 key购买 nike

假设我有以下文本:

The Text

是否可以在 Canvas 上写此文本,但使用 The粗体和 Text正常吗?

所以它看起来像这样:

文本

我知道如何将整个文本写成粗体,但我找不到单独格式化它的方法。

最佳答案

只要粗体字在前,您就可以简单地覆盖现有文本:

var canvas = document.body.appendChild(document.createElement("canvas"));
var size = canvas.width = canvas.height = 200;
var ctx = canvas.getContext("2d");
function draw() {
ctx.clearRect(0, 0, size, size);
ctx.font = "10pt Courier";
ctx.fillText("The Text", 100, 100);
setTimeout(function () {
ctx.font = "bold 10pt Courier";
ctx.fillText("The", 100, 100);
setTimeout(draw, 1000);
}, 1000);
}
draw();

编辑 1 - 回复评论

对于更复杂的字符串,可以使用 measuretext动态计算位置并切换字体:

/**
* drawText
* Draws a string on a canvas. Handles <b> tags.
* @param {{
* text: string,
* canvas: HTMLCanvasElement,
* offsetY?: number
* offsetX?: number,
* fontFamily?: string
* fontSize?: number
* clear?: boolean
* }} params
* @returns
*/
function drawText(params) {
//get parameters
var text = params.text !== void 0 ? params.text : "";
var canvas = params.canvas !== void 0 ? params.canvas : null;
if (canvas instanceof HTMLCanvasElement == false) {
console.error("You must provide a canvas to draw on");
return false;
}
var ctx = canvas.getContext("2d");
var fontFamily = params.fontFamily !== void 0 ? params.fontFamily : "Courier";
var fontSize = params.fontSize !== void 0 ? params.fontSize : 10;
var offsetX = params.offsetX !== void 0 ? params.offsetX : 0;
var offsetY = params.offsetY !== void 0 ? params.offsetY : 0;
//Split string by <b> tags
var formatted = text.split(/<\/b>|<b>/ig)
.filter(function (val) {
return val.length > 0;
});
//Clear canvas
if (params.clear !== void 0 ? params.clear : false) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
//set base font
ctx.font = fontSize + "pt " + fontFamily;
//Test if we start bold
var b = (text.substr(0, 1) == "<b");
for (var i = 0; i < formatted.length; i++) {
var t = formatted[i];
//Inverse bold on each step
b = !b;
if (b == true) {
ctx.font = fontSize + "pt " + fontFamily;
}
else {
ctx.font = "bold " + fontSize + "pt " + fontFamily;
}
//Calculate offset
var offset = i === 0 ? 0 : ctx.measureText(formatted.slice(0, i).join("")).width;
//Draw at position
ctx.fillText(t, offset + offsetX, offsetY);
}
return true;
}
//TEST
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.width = 230;
canvas.height = 30;
drawText({ text: "I Freaking <b>Love</b> Darth <b>Vader!</b>", canvas: canvas, offsetY: 10 });
drawText({ text: "I Freaking <b>Love</b> Darth <b>Vader!</b>", canvas: canvas, offsetY: 25 });

关于javascript - Canvas 上一篇文本的不同格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com