我是html5开发的新手,任何人都可以告诉我如何将文本移动到画布内的其他水平位置。
答案 0 :(得分:6)
以下是如何在屏幕上来回显示文字的示例:
<html>
<head>
<title>HTML 5 Animated Text</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var context;
var text = "";
var textDirection ="";
$(function()
{
context = document.getElementById("cvs").getContext("2d");
setInterval("animate()", 30);
textDirection ="right";
textXpos = 5;
text = "Animation!";
});
function animate() {
// Clear screen
context.clearRect(0, 0, 500, 500);
context.globalAlpha = 1;
context.fillStyle = '#fff';
context.fillRect(0, 0, 500, 500);
var metrics = context.measureText(text);
var textWidth = metrics.width;
if (textDirection == "right") {
textXpos += 10;
if (textXpos > 500 - textWidth) {
textDirection = "left";
}
}
else {
textXpos -= 10;
if (textXpos < 10) {
textDirection = "right";
}
}
context.font = '20px _sans';
context.fillStyle = '#FF0000';
context.textBaseline = 'top';
context.fillText ( text, textXpos, 180);
}
</script>
</head>
<body>
<div id="page">
<canvas id="cvs" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
答案 1 :(得分:1)
您还可以使用canvas store(),translate()和restore()方法为文本设置动画。 假设您要将文本从右侧移动到左侧,则可以使用以下代码段:
参考网站:http://www.authorcode.com/text-animation-in-html5/
var can,ctx,step,steps = 0, 延迟= 20;
function init() {
can = document.getElementById("MyCanvas1");
ctx = can.getContext("2d");
ctx.fillStyle = "blue";
ctx.font = "20pt Verdana";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
step = 0;
steps = can.height + 50;
RunTextRightToLeft();
}
function RunTextRightToLeft() {
step++;
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, step);
ctx.fillText("Welcome", 0, 0);
ctx.restore();
if (step == steps)
step = 0;
if (step < steps)
var t = setTimeout('RunTextRightToLeft()', delay);
}