Arc text in html

How to Curve/Arc Text Using CSS3/Canvas

Is there a way to curve / arc / bend only the bottom or top of text using CSS3

If you don’t care about browser support, i.e. if this only need to work in modern browser, then you may be able to do this by using SVG.

First, you’ll need to create the curved text in SVG. Then you SMIL animate the individual SVG element or CSS animate the individual SVG element.

Draw a Curved text using CSS

It isn’t super straightforward, but I suppose it could be done. Take a look at this article: Set Text on a Circle. Not the exact same thing, but same idea. You’d need to do it per character or section of words to do it.

A potentially easier solution would be to use Javascript/jQuery. But I know this doesn’t meet your CSS only requirement. Consider looking at ArcText.js as an option if you feel CSS isn’t doable for you.

Читайте также:  Farvater gumrf ru course view php id

There is also a tool that does this for you: CSS Warp — CSS Text to Path Generator. This would match exactly what you want, and generate the code for you for various browsers. I’ve never used it before, but seems nearly fool-proof.

CSS Warp

Here is an example using CSS Warp. I spent about 5 minutes. It gets you pretty close to what you want, and you can polish it up more. Then just use CSS to add the rest of the styling.

Curved Menu in CSS

You might be able to do it with canvas . See the answer to Is there a way to curve / arc text using CSS3 / Canvas for a sample. Note that canvas is not supported by IE8 and earlier, but it is otherwise pretty widely supported in modern browsers.

You might also want to look at this tutorial on drawing a sine wave with canvas since the menu in your image is somewhat sine wave shaped.

That’s a lot of work though for something like this, though. Instead, you can just make it a big image and use a map element to make an image map.

You could also consturct it out of a series of small images.

Text with arc direction in Canvas, but letters should keep vertical

The tool works by drawing the text normally, slicing it into 1px wide vertical strips, then redrawing those strips with vertical scaling and offset. Knowing how .drawImage() functions helps a lot in making this possible. Changing this algorithm to your needs is a matter of changing how the scaling and offset are calculated.

Two parameters are calculated for each strip: Offset and height. y controls the arc but is used directly to set the target height. h * 0.5 — offsetY / textHeight * y scales and offsets y to produce the offset.

Since y is derived almost directly from sin() , we can use that as the offset instead. The height would remain fixed so we use textHeight for that.

ctx.drawImage(os, i, 0, 1, textHeight, 
i, h * 0.5 - offsetY / textHeight * y, 1, y);
ctx.drawImage(os, i, 0, 1, textHeight, 
i, y, 1, textHeight);

This is the minimum change necessary. I’ll leave it as an exercise for yourself as to how to further clean up the code.

Make text curved with SVG, HTML and CSS for a web page title

First of all you can use text-anchor in combination with pathLength and startOffset to place the text in the middle. Here the the path length is 2, so the start offset is 1 and the anchor is set to «middle».

Second I changed the path a bit; scaled it and placed it in the top of the SVG (the arch hits y=0 in the middle). It is still the same shape. I used dominant-baseline to let the text «hang» under the path.

Now the viewbox can be scaled as well. If it has the height of 5 you can see the entire path, bit if you set it to 3 (second example) the following content will move closer.

An alternative could be to place the SVG as part of the CSS as a background in the content.

 



Curved Title
More content

Источник

Как сделать текст по кругу с помощью CSS или jQuery

Иногда на веб-страницу нужно добавить элемент с изогнутым или размещенным по кругу текстом. Например, логотип сайта. Но трансформация текста с помощью HTML и CSS может оказаться задачей не из легких. Благодаря возможностям CSS3 и jQuery это все-таки возможно.

Для реализации вам потребуется:

Просмотреть демо или скачать исходные файлы .

Как сделать текст по кругу с помощью CSS3 (сложный способ)

Рисунок, приведенный ниже, позволит понять, как реализовывать поставленную задачу с помощью CSS3.

Как сделать текст по кругу с помощью CSS3 (сложный способ)

Чтобы изогнуть текст с помощью CSS3, нужно разбить фразу на отдельные буквы. Это делается с помощью тегов span .

Для начала обернем текст в контейнер с ID simple_arc . Затем поместим каждую букву в тег span . Для дальнейшей настройки позиционирования в CSS используем уникальный класс для каждой буквы:

Для позиционирования текста добавим в ширину и высоту. Получается следующее:

Для каждого класса внутри всех элементов span воспользуемся селектором >. С его помощью мы выделяем все дочерние элементы созданного span- класса w вместе с порядковыми номерами. Далее используем селектор nth-of-type(n + 0), которым помечаем все элементы-потомки.

Затем задаем каждому элементу position:absolute. Положение измененных элементов корректируем с помощью свойства transform-origin .

#simple_arc>span[class^=w]:nth-of-type(n+0)

Источник

html5-canvas Text Rendering text along an arc.

This example shows how to render text along an arc. It includes how you can add functionality to the CanvasRenderingContext2D by extending its prototype.

This examples is derived from the stackoverflow answer Circular Text.

Example rendering

Example of circle text

Example code

The example adds 3 new text rendering functions to the 2D context prototype.

  • ctx.fillCircleText(text, x, y, radius, start, end, forward);
  • ctx.strokeCircleText(text, x, y, radius, start, end, forward);
  • ctx.measureCircleText(text, radius);
(function()< const FILL = 0; // const to indicate filltext render const STROKE = 1; var renderType = FILL; // used internal to set fill or stroke text const multiplyCurrentTransform = true; // if true Use current transform when rendering // if false use absolute coordinates which is a little quicker // after render the currentTransform is restored to default transform // measure circle text // ctx: canvas context // text: string of text to measure // r: radius in pixels // // returns the size metrics of the text // // width: Pixel width of text // angularWidth : angular width of text in radians // pixelAngularSize : angular width of a pixel in radians var measure = function(ctx, text, radius)< var textWidth = ctx.measureText(text).width; // get the width of all the text return < width : textWidth, angularWidth : (1 / radius) * textWidth, pixelAngularSize : 1 / radius >; > // displays text along a circle // ctx: canvas context // text: string of text to measure // x,y: position of circle center // r: radius of circle in pixels // start: angle in radians to start. // [end]: optional. If included text align is ignored and the text is // scaled to fit between start and end; // [forward]: optional default true. if true text direction is forwards, if false direction is backward var circleText = function (ctx, text, x, y, radius, start, end, forward) < var i, textWidth, pA, pAS, a, aw, wScale, aligned, dir, fontSize; if(text.trim() === "" || ctx.globalAlpha === 0)< // dont render empty string or transparent return; >if(isNaN(x) || isNaN(y) || isNaN(radius) || isNaN(start) || (end !== undefined && end !== null && isNaN(end))) < // throw TypeError("circle text arguments requires a number for x,y, radius, start, and end.") >aligned = ctx.textAlign; // save the current textAlign so that it can be restored at end dir = forward ? 1 : forward === false ? -1 : 1; // set dir if not true or false set forward as true pAS = 1 / radius; // get the angular size of a pixel in radians textWidth = ctx.measureText(text).width; // get the width of all the text if (end !== undefined && end !== null) < // if end is supplied then fit text between start and end pA = ((end - start) / textWidth) * dir; wScale = (pA / pAS) * dir; >else < // if no end is supplied correct start and end for alignment // if forward is not given then swap top of circle text to read the correct direction if(forward === null || forward === undefined)< if(((start % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2) >Math.PI) < dir = -1; >> pA = -pAS * dir ; wScale = -1 * dir; switch (aligned) < case "center": // if centered move around half width start -= (pA * textWidth )/2; end = start + pA * textWidth; break; case "right":// intentionally falls through to case "end" case "end": end = start; start -= pA * textWidth; break; case "left": // intentionally falls through to case "start" case "start": end = start + pA * textWidth; >> ctx.textAlign = "center"; // align for rendering a = start; // set the start angle for (var i = 0; i < text.length; i += 1) < // for each character aw = ctx.measureText(text[i]).width * pA; // get the angular width of the text var xDx = Math.cos(a + aw / 2); // get the yAxies vector from the center x,y out var xDy = Math.sin(a + aw / 2); if(multiplyCurrentTransform)< // transform multiplying current transform ctx.save(); if (xDy < 0) < // is the text upside down. If it is flip it ctx.transform(-xDy * wScale, xDx * wScale, -xDx, -xDy, xDx * radius + x, xDy * radius + y); >else < ctx.transform(-xDy * wScale, xDx * wScale, xDx, xDy, xDx * radius + x, xDy * radius + y); >>else < if (xDy < 0) < // is the text upside down. If it is flip it ctx.setTransform(-xDy * wScale, xDx * wScale, -xDx, -xDy, xDx * radius + x, xDy * radius + y); >else < ctx.setTransform(-xDy * wScale, xDx * wScale, xDx, xDy, xDx * radius + x, xDy * radius + y); >> if(renderType === FILL)< ctx.fillText(text[i], 0, 0); // render the character >else < ctx.strokeText(text[i], 0, 0); // render the character >if(multiplyCurrentTransform) < // restore current transform ctx.restore(); >a += aw; // step to the next angle > // all done clean up. if(!multiplyCurrentTransform) < ctx.setTransform(1, 0, 0, 1, 0, 0); // restore the transform >ctx.textAlign = aligned; // restore the text alignment > // define fill text var fillCircleText = function(text, x, y, radius, start, end, forward) < renderType = FILL; circleText(this, text, x, y, radius, start, end, forward); >// define stroke text var strokeCircleText = function(text, x, y, radius, start, end, forward) < renderType = STROKE; circleText(this, text, x, y, radius, start, end, forward); >// define measure text var measureCircleTextExt = function(text,radius) < return measure(this, text, radius); >// set the prototypes CanvasRenderingContext2D.prototype.fillCircleText = fillCircleText; CanvasRenderingContext2D.prototype.strokeCircleText = strokeCircleText; CanvasRenderingContext2D.prototype.measureCircleText = measureCircleTextExt; >)(); 

Function descriptions

This example adds 3 functions to the CanvasRenderingContext2D prototype . fillCircleText , strokeCircleText , and measureCircleText

CanvasRenderingContext2D.fillCircleText(text, x, y, radius, start, [end, [forward]]);

CanvasRenderingContext2D.strokeCircleText(text, x, y, radius, start, [end, [forward]]);

  • text: Text to render as String.
  • x,y: Position of circle center as Numbers.
  • radius: radius of circle in pixels
  • start: angle in radians to start.
  • [end]: optional. If included ctx.textAlign is ignored and the text is scaled to fit between start and end.
  • [forward]: optional default ‘true’. if true text direction is forwards, if ‘false’ direction is backward.

Both functions use the textBaseline to position the text vertically around the radius. For the best results use ctx.TextBaseline .

Functions will throw a TypeError is any of the numerical arguments as NaN.

If the text argument trims to an empty string or ctx.globalAlpha = 0 the function just drops through and does nothing.

CanvasRenderingContext2D.measureCircleText(text, radius);

 - **text:** String of text to measure. - **radius:** radius of circle in pixels. 

Returns a Object containing various size metrics for rendering circular text

 - **width:** Pixel width of text as it would normaly be rendered - **angularWidth:** angular width of text in radians. - **pixelAngularSize:** angular width of a pixel in radians. 

Usage examples

const rad = canvas.height * 0.4; const text = "Hello circle TEXT!"; const fontSize = 40; const centX = canvas.width / 2; const centY = canvas.height / 2; ctx.clearRect(0,0,canvas.width,canvas.height) ctx.font = fontSize + "px verdana"; ctx.textAlign = "center"; ctx.textBaseline = "bottom"; ctx.fillStyle = "#000"; ctx.strokeStyle = "#666"; // Text under stretched from Math.PI to 0 (180 - 0 deg) ctx.fillCircleText(text, centX, centY, rad, Math.PI, 0); // text over top centered at Math.PI * 1.5 ( 270 deg) ctx.fillCircleText(text, centX, centY, rad, Math.PI * 1.5); // text under top centered at Math.PI * 1.5 ( 270 deg) ctx.textBaseline = "top"; ctx.fillCircleText(text, centX, centY, rad, Math.PI * 1.5); // text over top centered at Math.PI * 1.5 ( 270 deg) ctx.textBaseline = "middle"; ctx.fillCircleText(text, centX, centY, rad, Math.PI * 1.5); // Use measureCircleText to get angular size var circleTextMetric = ctx.measureCircleText("Text to measure", rad); console.log(circleTextMetric.width); // width of text if rendered normally console.log(circleTextMetric.angularWidth); // angular width of text console.log(circleTextMetric.pixelAngularSize); // angular size of a pixel // Use measure text to draw a arc around the text ctx.textBaseline = "middle"; var width = ctx.measureCircleText(text, rad).angularWidth; ctx.fillCircleText(text, centX, centY, rad, Math.PI * 1.5); // render the arc around the text ctx.strokeStyle= "red"; ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(centX, centY, rad + fontSize / 2,Math.PI * 1.5 - width/2,Math.PI*1.5 + width/2); ctx.arc(centX, centY, rad - fontSize / 2,Math.PI * 1.5 + width/2,Math.PI*1.5 - width/2,true); ctx.closePath(); ctx.stroke(); 

NOTE: The text rendered is only an approximation of circular text. For example if two l’s are rendered the two lines will not be parallel, but if you render a «H» the two edges will be parallel. This is because each character is rendered as close as possible to the required direction, rather than each pixel being correctly transformed to create circular text.

NOTE: const multiplyCurrentTransform = true; defined in this example is used to set the transformation method used. If false the transformation for circular text rendering is absolute and does not depend on the current transformation state. The text will not be effected by any previous scale, rotate, or translate transforms. This will increase the performance of the render function, after the function is called the transform will be set to the default setTransform(1,0,0,1,0,0)

If multiplyCurrentTransform = true (set as default in this example) the text will use the current transform so that the text can be scaled translated, skewed, rotated, etc but modifying the current transform befor calling the fillCircleText and strokeCircleText functions. Depending on the current state of the 2D context this may be somewhat slower then multiplyCurrentTransform = false

pdf

PDF — Download html5-canvas for free

Источник

Оцените статью