如何为Plotly旋转动画添加暂停/播放按钮?
给Plotly 3D旋转动画添加暂停/播放功能
要实现暂停/播放功能,只需在原有的onRender JavaScript逻辑中加入状态控制,并添加一个交互按钮。以下是修改后的完整代码:
fig <- plot_ly(joined_most_recent, x = ~diff_hours_since_prev_review, y = ~`Average of time`, z = ~reps, color = ~lapses, colors=c("#5BBCD6", "red"), hoverinfo = 'text', text = ~paste0("Swahili: ", Swahili, "<br>", "Translation: ", English, "<br>", "Hours since previously studied: ", round(diff_hours_since_prev_review,1), "<br>", "Average Time Studied (s): ", round(`Average of time`,1), "<br>", "Number of Times Studied: ", reps)) fig <- fig %>% add_markers() fig <- fig %>% layout(scene = list(xaxis = list(title = 'Hours Since Last Studied'), camera = list(eye = list(x=1.8, y=1.8, z = 0.1)), yaxis = list(title = 'Average Time Studied (s)'), zaxis = list(title = 'Number of Views')), title = "Flashcards by Number of Views and Time Studied", margin = list(t = -5)) %>% onRender(" function(el, x){ var id = el.getAttribute('id'); var gd = document.getElementById(id); Plotly.update(id).then(attach); function attach() { let isPlaying = true; // 跟踪播放状态 let animationId; // 保存动画请求ID function run() { if (!isPlaying) return; // 非播放状态则停止执行 rotate('scene', Math.PI / 100); animationId = requestAnimationFrame(run); } run(); // 创建暂停/播放按钮 const controlBtn = document.createElement('button'); controlBtn.textContent = '暂停'; controlBtn.style.margin = '10px'; controlBtn.addEventListener('click', function() { isPlaying = !isPlaying; this.textContent = isPlaying ? '暂停' : '播放'; if (isPlaying) { run(); // 重新启动动画 } else { cancelAnimationFrame(animationId); // 取消动画请求 } }); // 将按钮添加到图表容器的父元素中 gd.parentNode.appendChild(controlBtn); function rotate(id, angle) { var eye0 = gd.layout[id].camera.eye var rtz = xyz2rtz(eye0); rtz.t += angle; var eye1 = rtz2xyz(rtz); Plotly.relayout(gd, id + '.camera.eye', eye1) } function xyz2rtz(xyz) { return { r: Math.sqrt(xyz.x * xyz.x + xyz.y * xyz.y), t: Math.atan2(xyz.y, xyz.x), z: xyz.z }; } function rtz2xyz(rtz) { return { x: rtz.r * Math.cos(rtz.t), y: rtz.r * Math.sin(rtz.t), z: rtz.z }; } }; } ") fig
关键修改说明:
- 状态变量:新增
isPlaying标记当前是否处于播放状态,animationId用于存储requestAnimationFrame的返回值,方便后续取消动画。 - 动画控制逻辑:修改
run函数,仅在isPlaying为true时继续执行动画;点击按钮时切换状态,通过cancelAnimationFrame暂停动画,再次点击则调用run()恢复。 - 交互按钮:动态创建按钮并绑定点击事件,按钮文本会随状态切换为“暂停”或“播放”,并添加到图表旁方便操作。
内容的提问来源于stack exchange,提问作者user20934000
相关产品推荐
相关产品推荐

