appendChild()するだけでは動かなかった。
ChatGPTに聞いて試行錯誤したのでメモ。
公式のドキュメントがあれば教えてください🙇
load()とplay()を呼ぶのがポイントみたい。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lottie Player Test</title>
<script src="https://unpkg.com/dotlottie-player"></script>
<style>
.container, .target {
border: 1px solid #ccc;
padding: 20px;
margin: 20px;
min-height: 350px;
}
</style>
</head>
<body>
<div id="container" class="container">
<dotlottie-player
id="lottiePlayer"
src="https://assets2.lottiefiles.com/packages/lf20_x62chJ.json"
background="transparent"
speed="1"
style="width: 300px; height: 300px;"
loop
autoplay>
</dotlottie-player>
</div>
<div id="target" class="target"></div>
<button onclick="movePlayer()">Move Player</button>
<script>
document.addEventListener("DOMContentLoaded", function() {
const player = document.getElementById('lottiePlayer');
player.addEventListener('ready', function() {
console.log('Lottie player is ready');
});
player.addEventListener('error', function(event) {
console.error('Lottie player error:', event);
});
});
function movePlayer() {
const player = document.getElementById('lottiePlayer');
const target = document.getElementById('target');
if (player && target) {
const parent = player.parentNode;
target.appendChild(player);
// プレイヤーを再度再生
player.load(player.src); // srcを再設定してロード
player.play(); // 再生
} else {
console.error('player or target element is not found');
}
}
</script>
</body>
</html>