想要创建一个如下所示的Bridge Text Effect
,我尝试使用 arctext 但没有帮助。我尝试使用 google id 但它不理解 Bridge 文本形状。
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
context.font = '30pt Calibri';
// textAlign aligns text horizontally relative to placement
context.textAlign = 'center';
// textBaseline aligns text vertically relative to font style
context.textBaseline = 'middle';
context.fillStyle = 'blue';
context.fillText('BRIDGE TEXT', x, y);
</script>
</body>
</html>
最佳答案
位移
至少有两种方法可以实现弯曲文本效果 - 两者都具有相同的像素位移原理(将它们移出相对于真实位置的位置),这只是我们使用哪种方法的问题这个。
在下面的演示中,我将使用内部 drawImage
方法进行简单的切片。或者,我们可以迭代像素缓冲区并手动投影像素,但对于这种情况,在我看来,使用切片更简单,而且我们可以免费获得抗锯齿功能。
示例+演示
以下是实现此目的的一种方法的完整示例(请参阅 slider 和自定义文本的演示):
<强> ONLINE DEMO HERE
结果将是:
var ctx = demo.getContext('2d'), /// get canvas
font = '64px impact', /// define font
w = demo.width, /// cache width and height
h = demo.height,
curve, /// curve for our text
offsetY, /// offset from top (see note)
bottom, /// bottom origin
textHeight, /// height of text
angleSteps = 180 / w, /// angle steps per pixel
i = w, /// counter (for x)
y,
os = document.createElement('canvas'), /// off-screen canvas
octx = os.getContext('2d');
/// set off-screen canvas same size as our demo canavs
os.width = w;
os.height = h;
/// prep text for off-screen canvas
octx.font = font;
octx.textBaseline = 'top';
octx.textAlign = 'center';
/// main render function
function renderBridgeText() {
/// snipped... get various data (see demo for detail)
/// clear canvases
octx.clearRect(0, 0, w, h);
ctx.clearRect(0, 0, w, h);
/// draw the text (see demo for details)
octx.fillText(iText.value, w * 0.5, 0);
/// slide and dice (MAIN)
i = w;
while (i--) {
/// calc distance based on curve (=radius) and x position
y = bottom - curve * Math.sin(i * angleSteps * Math.PI / 180);
/// draw the slice for this vertical line
ctx.drawImage(os, i, offsetY, 1, textHeight,
i, offsetY, 1, y);
}
}
关于偏移的注意:偏移可以有很多东西 - 在这个演示中,我让它成为文本的顶部源,以“纠正”一点弯曲,因为文本没有绘制在最顶部(由于各种字形几何形状)我不会在这里讨论) - 你会在 Chrome 和 Firefox 之间清楚地看到这一点,因为文本的渲染方式不同。
该演示允许您更改文本并调整一些参数,以便您可以看到它们对文本的影响。
它是如何工作的
宽度首先除以我们想要在 x 轴上移动的像素数。这为我们提供了每个像素步长所需使用的增量 Angular 。
然后,我们使用正弦函数,以曲线为半径,根据 y 轴的 Angular 计算基本距离。由于增量 Angular 现在对应于基于 x 位置的从 0 到 180 的 Angular ,这将为我们提供一条与中心绘制的文本宽度相匹配的漂亮曲线。
我们从底部减去该值以获得文本底部的 y 位置。
然后我们从源中选择一个正常大小的切片,一像素厚,然后根据 y 值将其缩放到目标。这样就可以了。
关于javascript - HTML5 Canvas 中的桥接文本效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19460533/