requestAnimationFrame yes HTML5 Essential functions for games and animation , be relative to setTimeout or setInterval It has two advantages , One is that its registered callback function is synchronized with the browser's rendering , Never mind Timer The time interval is too long or too short . Second, the time interval is relative to Timer To be stable ,requestAnimationFrame The highest execution frequency of the registered callback function is 60FPS, Although in HTML5 It's usually not in the game , But the time interval between its two calls is longer than Timer Stable . Some time ago I was CanTK Runtime I simulated it myself in the library requestAnimationFrame, For a deeper understanding Chrome To realize requestAnimationFrame Method , Took a little time to read Blink Code for .

requestAnimationFrame The basic usage is as follows :

var start = null;
var element = document.getElementById("SomeElementYouWantToAnimate"); function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
element.style.left = Math.min(progress/10, 200) + "px";
if (progress < 2000) {
window.requestAnimationFrame(step);
}
} window.requestAnimationFrame(step);

I'm more concerned about the registration and calling process of callback functions :

  • 1. Register the implementation of the callback function .

(WebKit/Source/core/dom/ScriptedAnimationController.cpp)

ScriptedAnimationController::CallbackId ScriptedAnimationController::registerCallback(FrameRequestCallback* callback)
{
CallbackId id = m_callbackCollection.registerCallback(callback);
scheduleAnimationIfNeeded();
return id;
}

You need to request redrawing after registration ,scheduleAnimationIfNeeded It will eventually be transferred to ThreadProxy::SendCommitRequestToImplThreadIfNeeded:

(cc/trees/thread_proxy.cc)

bool ThreadProxy::SendCommitRequestToImplThreadIfNeeded(
CommitPipelineStage required_stage) {
DCHECK(IsMainThread());
DCHECK_NE(NO_PIPELINE_STAGE, required_stage);
bool already_posted =
main().max_requested_pipeline_stage != NO_PIPELINE_STAGE;
main().max_requested_pipeline_stage =
std::max(main().max_requested_pipeline_stage, required_stage);
if (already_posted)
return false;
Proxy::ImplThreadTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&ThreadProxy::SetNeedsCommitOnImplThread,
impl_thread_weak_ptr_));
return true;
} void ThreadProxy::SetNeedsCommitOnImplThread() {
TRACE_EVENT0("cc", "ThreadProxy::SetNeedsCommitOnImplThread");
DCHECK(IsImplThread());
impl().scheduler->SetNeedsBeginMainFrame();
} void Scheduler::SetNeedsBeginMainFrame() {
state_machine_.SetNeedsBeginMainFrame();
ProcessScheduledActions();
}
  • 2. Implementation of callback function .

WebKit/Source/core/dom/ScriptedAnimationController.cpp

void ScriptedAnimationController::executeCallbacks(double monotonicTimeNow)
{
// dispatchEvents() runs script which can cause the document to be destroyed.
if (!m_document)
return; double highResNowMs = 1000.0 * m_document->loader()->timing().monotonicTimeToZeroBasedDocumentTime(monotonicTimeNow);
double legacyHighResNowMs = 1000.0 * m_document->loader()->timing().monotonicTimeToPseudoWallTime(monotonicTimeNow);
m_callbackCollection.executeCallbacks(highResNowMs, legacyHighResNowMs);
}
void FrameRequestCallbackCollection::executeCallbacks(double highResNowMs, double highResNowMsLegacy)
{
// First, generate a list of callbacks to consider. Callbacks registered from this point
// on are considered only for the "next" frame, not this one.
ASSERT(m_callbacksToInvoke.isEmpty());
m_callbacksToInvoke.swap(m_callbacks); for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
FrameRequestCallback* callback = m_callbacksToInvoke[i].get();
if (!callback->m_cancelled) {
TRACE_EVENT1("devtools.timeline", "FireAnimationFrame", "data", InspectorAnimationFrameEvent::data(m_context, callback->m_id));
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireAnimationFrame(m_context, callback->m_id);
if (callback->m_useLegacyTimeBase)
callback->handleEvent(highResNowMsLegacy);
else
callback->handleEvent(highResNowMs);
InspectorInstrumentation::didFireAnimationFrame(cookie);
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "UpdateCounters", TRACE_EVENT_SCOPE_THREAD, "data", InspectorUpdateCountersEvent::data());
}
} m_callbacksToInvoke.clear();
}

This line of code m_callbacksToInvoke.swap(m_callbacks); It's interesting , In the loop execution of callbacks There will be new callback Sign in , When I do this function , I haven't seen this code , It took a little effort to figure out what to do .

The code above is created by RenderWidgetCompositor::BeginMainFrame Transferred :

(src/content/renderer/gpu/render_widget_compositor.cc)

void RenderWidgetCompositor::BeginMainFrame(const cc::BeginFrameArgs& args) {
double frame_time_sec = (args.frame_time - base::TimeTicks()).InSecondsF();
double deadline_sec = (args.deadline - base::TimeTicks()).InSecondsF();
double interval_sec = args.interval.InSecondsF();
WebBeginFrameArgs web_begin_frame_args =
WebBeginFrameArgs(frame_time_sec, deadline_sec, interval_sec);
compositor_deps_->GetRendererScheduler()->WillBeginFrame(args);
widget_->webwidget()->beginFrame(web_begin_frame_args);
}

requestAnimationFrame stay Chrome More articles on the implementation of

  1. LocalStorage stay Chrome The realization in

    Some time ago, we were realizing CanTK-Runtime when , Also in V8 Based on the simulation of the browser LocaleStorage function , It's very simple : Every domain The data is stored in separate files , Because only one game runs at a time , the ...

  2. 【27 front end 】base Label with href Attributes make chrome Inside svg Elements url invalid

    One chrome The problem of , But the specific reason is not clear . The trigger condition :chrome browser base In the label href When properties have values Trigger problem :svg If the elements are useful url The filter and blur , It will fail , stay firefox Li He IE10 ...

  3. It's fun ! Directly in Chrome Grabbing data from the Internet

    A small test found that it can do questions automatically , So I want to see if I can get the corresponding question bank through script , Just to learn JS Asynchronous operations . It took a day , It's a good run , A lot of potholes . Write it down and share it . 1.JS How to execute in sequence JS It has powerful asynchronous operation ...

  4. Directly in Chrome Grabbing data from the Internet

    A small test found that it can do questions automatically , So I want to see if I can get the corresponding question bank through script , Just to learn JS Asynchronous operations . It took a day , It's a good run , A lot of potholes . Write it down and share it . 1.JS How to execute in sequence JS It has powerful asynchronous operation ...

  5. favicon.ico stay chrome It's normal , stay ie,edge It doesn't show in the browser

    Code : <head> <meta charset="UTF-8"> <link href="imgs/favicon.ico" r ...

  6. Close on chrome Use the function of double finger forward and backward page in

    defaults write com.google.Chrome AppleEnableSwipeNavigateWithScrolls -bool FALSE

  7. stay CHROME In the installation VIMIUM plug-in unit , Convenient operation

    VIMIUM How to use plug-ins VIMIUM The list of commands Webpage navigation j, : Scroll down the page k, : Scroll up the page h : scroll left l : Scroll right gg : Scroll to the top of the page G : Scroll to the bottom of the page : Turn up ...

  8. How to be in CHROME Debug the front-end code in ?

    I used to see that the front end was very well tuned , I just read here , Make a note , Rehearsed , It's a little bit divine !!! :) <!DOCTYPE html> <html lang="en"> & ...

  9. Chrome The request in is wrong &quot;CAUTION: Provisional headers are shown&quot; What does that mean? ?

    In the debugger, the file display prompt is  CAUTION: Provisional headers are shown, But the direct copy link access resources can be normal access , The final discovery is https problem , Resource adoption ssl agreement , ...

Random recommendation

  1. cocos2dx Realization flappybird

    Two days ago, I saw a webpage version of flappy bird, Hang on 360 Gaming platform , Played for a while, scored very low , I really want to make one myself . Just these two days, the work of dazzle dance has been cleared , Just play with it . design sketch Layout class GameScene.h ...

  2. install ubuntu And installation ubuntu List of software to be installed after

    install ubuntu Lao Maotao enters win pe Fix startup stay win pe Now make ubuntu Installation disk of , The only software used is ultraISO Refer to the article in the section below the blog   http://jingyan.baidu. ...

  3. 15 Variables &amp; Best practices for method naming 【 turn 】

    Original address :15 Best Practices of Variable & Method Naming Different code segments have different naming lengths . Generally speaking , Cycle counter (loop counters) use 1 position ...

  4. WebMagic Open source vertical crawler introduction

    WebMagic The project code is divided into two parts: core and extension . The core part of the (webmagic-core) It's a streamlined . Modular implementation of crawler , And the extension includes some convenient . Practical functions .WebMagic The architecture design of is based on Scrap ...

  5. Amazon Of AWS The bill doesn't look very convenient

    Issued a PDF Receipt in the form of , It's just the charge ,EC2 The details below don't have . DetailAmazon Simple Notification Service $0.00Charges $0.00Estimat ...

  6. c++ :: scope operator

    c++ :: scope operator Scope : The scope of variables in a program can be simply divided into : Global scope , Local scope , Statement scope scope priority : The smaller the scope, the higher the priority :"::" If you want to play a role in local variables ...

  7. C# Realize Unicom SMS Sgip Protocol program source code

    This program is for China Unicom Sgip Protocol program interface , It is suitable for the company applying for SMS sending port in China Unicom . SMS group sending has become a software system . Network marketing and other essential application tools . It can be used in SMS verification . Mass distribution of information . Game virtual goods purchase . Event reminder . ...

  8. Simple export and download excel Methods

    Simple export excel Method /// <summary> /// Excel Package download /// </summary> /// <returns></returns&g ...

  9. Use COOKIE To realize the login VS Use SESSION To realize the login

    notes : The code used in this article is based on PHP, The logic of other languages is the same . One : Use COOKIE Implement login authentication Use cookie The way to log in , Mainly through some one-way encryption information verification . such as admin After the user logs in , The server generates a co ...

  10. bzoj 4358 Permu - Mo team algorithm - Linked list

    Subject portal Gateways that require advanced permissions The main idea of the topic Given a full permutation , Ask the maximum length of a continuous segment of a range of values in an interval . Consider using the moose algorithm . Insert one number at a time $x$, The effect on the range can be divided into 4 In this case : $x - 1$, ...