[英]Using trigonometry to animate HTML5 canvas, but how to position this square?
[英]How to animate text weight using Leon Sans with HTML5 Canvas
使用允許通過 canvas 進行動態動畫的字體Leon Sans ,我如何對給定文本字符串的重量進行動畫處理,當每個字母變粗時會稍微令人震驚,如下所示:
(所需效果的動畫 gif 可在README中的“重量變化”列表項上方的“有什么特別之處”部分中查看。)
我有一個用這個建議的起始代碼正確繪制的字符串:
let leon, canvas, ctx;
const sw = 800;
const sh = 600;
const pixelRatio = 2;
function init() {
canvas = document.createElement('canvas');
document.body.appendChild(canvas);
ctx = canvas.getContext("2d");
canvas.width = sw * pixelRatio;
canvas.height = sh * pixelRatio;
canvas.style.width = sw + 'px';
canvas.style.height = sh + 'px';
ctx.scale(pixelRatio, pixelRatio);
leon = new LeonSans({
text: 'animate this text',
color: ['#000000'],
size: 80,
weight: 200
});
requestAnimationFrame(animate);
}
function animate(t) {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, sw, sh);
const x = (sw - leon.rect.w) / 2;
const y = (sh - leon.rect.h) / 2;
leon.position(x, y);
leon.draw(ctx);
}
window.onload = () => {
init();
};
字體的創建者向我提出了使用以下代碼片段的建議:
this.leons_ = [];
this.text_ = String('animate this text').split('');
this.leonTotal_ = this.text_.length;
for (let i = 0; i < this.leonTotal_; i++) {
const ls = new LeonSans({
text: this.text_[i],
color: ['blue'],
size: 100,
weight: 200
});
this.leons_.push(ls);
}
但我仍然無法讓它工作。 當我嘗試以這種方式合並它時,屏幕上根本沒有任何文字:
let leon, canvas, ctx;
let leons_, text_, leonTotal_;
const sw = 800;
const sh = 600;
const pixelRatio = 2;
function init() {
canvas = document.createElement('canvas');
document.body.appendChild(canvas);
ctx = canvas.getContext("2d");
canvas.width = sw * pixelRatio;
canvas.height = sh * pixelRatio;
canvas.style.width = sw + 'px';
canvas.style.height = sh + 'px';
ctx.scale(pixelRatio, pixelRatio);
leons_ = [];
text_ = String('animate this text').split('');
leonTotal_ = text_.length;
for (let i = 0; i < leonTotal_; i++) {
const ls = new LeonSans({
text: text_[i],
color: ['blue'],
size: 100,
weight: 200
});
leons_.push(ls);
}
requestAnimationFrame(animate);
}
function animate(t) {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, sw, sh);
const x = (sw - leon.rect.w) / 2;
const y = (sh - leon.rect.h) / 2;
leon.position(x, y);
leon.draw(ctx);
}
window.onload = () => {
init();
};
我得到控制台錯誤:
leon.js:5316 Uncaught TypeError: Cannot read property 'rect' of undefined
參考這一行:
const x = (sw - leon.rect.w) / 2;
但我懷疑在專門調試該錯誤之前我需要修復我的方法。
有任何想法嗎? (請隨意重新混合上面鏈接的 Glitch 項目。)
謝謝。
對於任何有興趣的人,我想通了。
從我上面失敗的嘗試開始,我可以使用我創建的數組leons_
和TweenMax.staggerFromTo
來循環遍歷數組中的每個字母:
TweenMax.staggerFromTo(
leons_,
1,
{
weight: minWeight,
size: sw * leonHeightRatio
},
{
weight: maxWeight,
size: sw * leonHeightRatioLarge,
repeat: -1,
yoyo: true,
ease: Power2.easeInOut
},
0.1);
在此處查看工作代碼示例: https://leon-sans-staggered-weight-size-animations.glitch.me/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.