HTML5 Canvas打字机效果与文字包装? [英] HTML5 Canvas typewriter effect with word wrapping?

查看:162
本文介绍了HTML5 Canvas打字机效果与文字包装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML5画布上获得一个动画打字机效果,但我真的很努力与Word Wrapping。

I'm trying to get an animated typewriter effect on a HTML5 Canvas but I'm really struggling with Word Wrapping.

这是我的Shapes.js在一个Gist : https://gist.github.com/Jamesking56/0d7df54473085b3c5394

Here's my Shapes.js in a Gist: https://gist.github.com/Jamesking56/0d7df54473085b3c5394

在这里,我创建了一个Text对象,它有很多方法。其中一个名为 typeText()

In there, I've created a Text object which has lots of methods. One of which is called typeText().

typeText $ c>基本上从打字效果开始,但它一直在下降的边缘,我真的很努力找到一种固定的字包裹的方式。

typeText() basically starts off the typewriting effect but it keeps on falling off the edge and I'm really struggling to find a way of fixing word wrapping.

任何人都可以指导

推荐答案

我使用的解决方案大致是:

A solution I have used is roughly:

var maxWidth = 250;
var text = 'lorem ipsum dolor et sit amet...';

var words = text.split(' ');
var line = [words[0]]; //begin with a single word

for(var i=1; i<words.length; i++){
    while(ctx.measureText(line.join(' ')) < maxWidth && i<words.length-1){
        line.push(words[i++]);
    }
    if(i < words.length-1) { //Loop ended because line became too wide
        line.pop(); //Remove last word
        i--; //Take one step back
    }
    //Ouput the line
}


$ b b

由于似乎没有办法测量输出文本的高度,因此您需要手动偏移每一行输出的硬编码行高度。

Since there seems to be no way to measure the height of the output text, you need to manually offset each line you output by some hardcoded line height.

这篇关于HTML5 Canvas打字机效果与文字包装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆