gpt4 book ai didi

javascript - 文本旋转 HTML 5 Canvas

转载 作者:行者123 更新时间:2023-11-30 17:35:04 24 4
gpt4 key购买 nike

我想在 Canvas 上添加一些文本并将文本像风车一样旋转一圈。

你会怎么做。我只想要一个连续的循环,其中文本永远不会停止旋转。

function showCircularNameRotating(string, startAngle, endAngle){
//context.clearRect(0, 0, canvas.width, canvas.height);
circle = {
x: canvas.width/2,
y: canvas.height/2,
radius: 200
};

var radius = circle.radius,
angleDecrement = (startAngle - endAngle)/string.length-1),
angle = parseFloat(startAngle),
index = 0,
character;

context.save();
while(index <string.length){
character = stringcharAt(index);
context.save();
context.beginPath();
context.translate(circle.x + Math.cos(angle) * radius,
circle.y - Math.sin(angle) * radius);
context.rotate(math.PI/2 - angle);

context.fillText(charater, 0,0);
context.strokeText(character,0,0);
angle -= angleDecrement;
index++;
context.restore();
}
context.restore();

}

drawCircularText("Clockwise", Math.PI*2, Math.PI/8);

最佳答案

旋转文本的简单代码可能如下所示 - 根据需要采用:

var ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
cx = w * 0.5, // center of canvas
cy = h * 0.5,
angleStep = 0.1,
txt = 'PINWHEEL TEXT';

ctx.font = 'bold 30px sans-serif'; // set font
ctx.textAlign = 'center'; // align text in center
ctx.textBaseline = 'middle';

(function rotate() {
ctx.clearRect(0, 0, w, h); // clear canvas
ctx.translate(cx, cy); // translate to center of rotation
ctx.rotate(angleStep); // rotate (accumulative)
ctx.translate(-cx, -cy); // translate back
ctx.fillText(txt, cx, cy); // draw text at rotated center

requestAnimationFrame(rotate); // loop
})();

Live demo

更新

它的通用函数(将 Canvas 和上下文放在外面):

function rotateText(ctx, txt, font, angleStep, cx, cy) {

var w = ctx.canvas.width,
h = ctx.canvas.height;

cx = cx || w * 0.5; // defaults to center if cx/cy isn't given
cy = cy || h * 0.5;

ctx.font = font;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';

(function rotate() {
ctx.clearRect(0, 0, w, h); // clear canvas
ctx.translate(cx, cy); // translate to center of rotation
ctx.rotate(angleStep); // rotate (accumulative)
ctx.translate(-cx, -cy); // translate back
ctx.fillText(txt, cx, cy); // draw text at rotated center

requestAnimationFrame(rotate); // loop
})();
}

现在只需调用:

rotateText(ctx, 'MyText', '32px myfont', 0.1);

rotateText(ctx, 'MyText', '32px myfont', 0.1, centerX, centerY);

关于javascript - 文本旋转 HTML 5 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22211288/

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