Javascript Chrome requestAnimationFrame问题
相关主题: 我一直在为触摸设备构建一个小部件,以实现平滑的动画效果,我找到的帮助我实现这一点的工具之一就是Chrome Memory Timeline屏幕 这对我评估rAF循环中的内存消耗有点帮助,但我现在在Chrome30中观察到的一些行为让我感到困扰 当最初进入我的页面(其中运行着rAF循环)时,我看到了这一点 看起来不错。如果我已经完成了我的工作,并且在我的内部循环中消除了对象分配,那么就不应该有锯齿。这与链接主题一致,也就是说,无论何时使用rAF,Chrome都有内置漏洞。(哎呀!) 当我开始在页面中做各种各样的事情时,它会变得更有趣 我并没有做任何不同的事情,只是暂时添加两个元素,使CSS3 3D变换样式应用于一些帧,然后我停止与它们交互 我们在这里看到的是Chrome报告,rAF的每一次发射(16ms)都会导致Javascript Chrome requestAnimationFrame问题,javascript,html,google-chrome,requestanimationframe,Javascript,Html,Google Chrome,Requestanimationframe,相关主题: 我一直在为触摸设备构建一个小部件,以实现平滑的动画效果,我找到的帮助我实现这一点的工具之一就是Chrome Memory Timeline屏幕 这对我评估rAF循环中的内存消耗有点帮助,但我现在在Chrome30中观察到的一些行为让我感到困扰 当最初进入我的页面(其中运行着rAF循环)时,我看到了这一点 看起来不错。如果我已经完成了我的工作,并且在我的内部循环中消除了对象分配,那么就不应该有锯齿。这与链接主题一致,也就是说,无论何时使用rAF,Chrome都有内置漏洞。(哎呀!) 当
动画帧发射x3
这种重复以及重复的速率单调地增加,直到页面刷新为止
您已经可以在第二个屏幕盖中看到锯齿斜率在最初从动画帧激发
跳到动画帧激发X3
后显著增加
过了一会儿,它跳到了x21
:
看起来我的代码被额外运行了很多次,但所有额外的多次运行都只是浪费热量和计算
当我拍摄第三个屏幕时,我的Macbook热得很厉害。不久之后,在我能够将时间线拖到最后一位(大约8分钟)以查看x
数字增加到什么之前,inspector窗口变得完全无响应,并且提示我的页面已无响应,必须终止
以下是页面中运行的全部代码:
// ============================================================================
// Copyright (c) 2013 Steven Lu
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ============================================================================
// This is meant to be a true velocity verlet integrator, which means sending
// in for the force and torque a function (not a value). If the forces provided
// are evaluated at the current time step then I think we are left with plain
// old Euler integration. This is a 3 DOF integrator that is meant for use
// with 2D rigid bodies, but it should be equally useful for modeling 3d point
// dynamics.
// this attempts to minimize memory waste by operating on state in-place.
function vel_verlet_3(state, acc, dt) {
var x = state[0],
y = state[1],
z = state[2],
vx = state[3],
vy = state[4],
vz = state[5],
ax = state[6],
ay = state[7],
az = state[8],
x1 = x + vx * dt + 0.5 * ax * dt * dt,
y1 = y + vy * dt + 0.5 * ay * dt * dt,
z1 = z + vz * dt + 0.5 * az * dt * dt, // eqn 1
a1 = acc(x1, y1, z1),
ax1 = a1[0],
ay1 = a1[1],
az1 = a1[2];
state[0] = x1;
state[1] = y1;
state[2] = z1;
state[3] = vx + 0.5 * (ax + ax1) * dt,
state[4] = vy + 0.5 * (ay + ay1) * dt,
state[5] = vz + 0.5 * (az + az1) * dt; // eqn 2
state[6] = ax1;
state[7] = ay1;
state[8] = az1;
}
// velocity indepedent acc --- shit this is gonna need to change soon
var acc = function(x, y, z) {
return [0,0,0];
};
$("#lock").click(function() {
var values = [Number($('#ax').val()), Number($('#ay').val()), Number($('#az').val())];
acc = function() {
return values;
};
});
// Obtain the sin and cos from an angle.
// Allocate nothing.
function getRotation(angle, cs) {
cs[0] = Math.cos(angle);
cs[1] = Math.sin(angle);
}
// Provide the localpoint as [x,y].
// Allocate nothing.
function global(bodystate, localpoint, returnpoint) {
getRotation(bodystate[2], returnpoint);
// now returnpoint contains cosine+sine of angle.
var px = bodystate[0], py = bodystate[1];
var x = localpoint[0], y = localpoint[1];
// console.log('global():', cs, [px, py], localpoint, 'with', [x,y]);
// [ c -s px ] [x]
// [ s c py ] * [y]
// [1]
var c = returnpoint[0];
var s = returnpoint[1];
returnpoint[0] = c * x - s * y + px;
returnpoint[1] = s * x + c * y + py;
}
function local(bodystate, globalpoint, returnpoint) {
getRotation(bodystate[2], returnpoint);
// now returnpoint contains cosine+sine of angle
var px = bodystate[0], py = bodystate[1];
var x = globalpoint[0], y = globalpoint[1];
// console.log('local():', cs, [px, py], globalpoint, 'with', [x,y]);
// [ c s ] [x - px]
// [ -s c ] * [y - py]
var xx = x - px, yy = y - py;
var c = returnpoint[0], s = returnpoint[1];
returnpoint[0] = c * xx + s * yy;
returnpoint[1] = -s * xx + c * yy;
}
var cumulativeOffset = function(element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return {
top: top,
left: left
};
};
// helper to create/assign position debugger (handles a single point)
// offset here is a boundingclientrect offset and needs window.scrollXY correction
var hasDPOffsetRun = false;
var dpoff = false;
function debugPoint(position, id, color, offset) {
if (offset) {
position[0] += offset.left;
position[1] += offset.top;
}
// if (position[0] >= 0) { console.log('debugPoint:', id, color, position); }
var element = $('#point' + id);
if (!element.length) {
element = $('<div></div>')
.attr('id', 'point' + id)
.css({
pointerEvents: 'none',
position: 'absolute',
backgroundColor: color,
border: '#fff 1px solid',
top: -2,
left: -2,
width: 2,
height: 2,
borderRadius: 300,
boxShadow: '0 0 6px 0 ' + color
});
$('body').append(
$('<div></div>')
.addClass('debugpointcontainer')
.css({
position: 'absolute',
top: 0,
left: 0
})
.append(element)
);
if (!hasDPOffsetRun) {
// determine the offset of the body-appended absolute element. body's margin
// is the primary offender that tends to throw a wrench into our shit.
var dpoffset = $('.debugpointcontainer')[0].getBoundingClientRect();
dpoff = [dpoffset.left + window.scrollX, dpoffset.top + window.scrollY];
hasDPOffsetRun = true;
}
}
if (dpoff) {
position[0] -= dpoff[0];
position[1] -= dpoff[1];
}
// set position
element[0].style.webkitTransform = 'translate3d(' + position[0] + 'px,' + position[1] + 'px,0)';
}
var elements_tracked = [];
/*
var globaleventhandler = function(event) {
var t = event.target;
if (false) { // t is a child of a tracked element...
}
};
// when the library is loaded the global event handler for GRAB is not
// installed. It is lazily installed when GRAB_global is first called, and so
// if you only ever call GRAB then the document does not get any handlers
// attached to it. This will remain unimplemented as it's not clear what the
// semantics for defining behavior are. It's much more straightforward to use
// the direct API
function GRAB_global(element, custom_behavior) {
// this is the entry point that will initialize a grabbable element all state
// for the element will be accessible through its __GRAB__ element through
// the DOM, and the DOM is never accessed (other than through initial
// assignment) by the code.
// event handlers are attached to the document, so use GRAB_direct if your
// webpage relies on preventing event bubbling.
if (elements_tracked.indexOf(element) !== -1) {
console.log('You tried to call GRAB() on an element more than once.',
element, 'existing elements:', elements_tracked);
}
elements_tracked.push(element);
if (elements_tracked.length === 1) { // this is the initial call
document.addEventListener('touchstart', globaleventhandler, true);
document.addEventListener('mousedown', globaleventhandler, true);
}
}
// cleanup function cleans everything up, returning behavior to normal.
// may provide a boolean true argument to indicate that you want the CSS 3D
// transform value to be cleared
function GRAB_global_remove(cleartransform) {
document.removeEventListener('touchstart', globaleventhandler, true);
document.removeEventListener('mousedown', globaleventhandler, true);
}
*/
var mousedownelement = false;
var stop = false;
// there is only one mouse, and the only time when we need to handle release
// of pointer is when the one mouse is let go somewhere far away.
function GRAB(element, onfinish, center_of_mass) {
// This version directly assigns the event handlers to the element
// it is less efficient but more "portable" and self-contained, and also
// potentially more friendly by using a regular event handler rather than
// a capture event handler, so that you can customize the grabbing behavior
// better and also more easily define it per element
var offset = center_of_mass;
var pageOffset = cumulativeOffset(element);
var bcrOffset = element.getBoundingClientRect();
bcrOffset = {
left: bcrOffset.left + window.scrollX,
right: bcrOffset.right + window.scrollX,
top: bcrOffset.top + window.scrollY,
bottom: bcrOffset.bottom + window.scrollY
};
if (!offset) {
offset = [element.offsetWidth / 2, element.offsetHeight / 2];
}
var model = {
state: [0, 0, 0, 0, 0, 0, 0, 0, 0],
offset: offset,
pageoffset: bcrOffset // remember, these values are pre-window.scroll[XY]-corrected
};
element.__GRAB__ = model;
var eventhandlertouchstart = function(event) {
// set
var et0 = event.touches[0];
model.anchor = [0,0];
local(model.state, [et0.pageX - bcrOffset.left - offset[0], et0.pageY - bcrOffset.top - offset[1]], model.anchor);
debugPoint([et0.pageX, et0.pageY], 1, 'red');
event.preventDefault();
requestAnimationFrame(step);
};
var eventhandlermousedown = function(event) {
console.log('todo: reject right clicks');
// console.log('a', document.body.scrollLeft);
// set
// model.anchor = [event.offsetX - offset[0], event.offsetY - offset[1]];
model.anchor = [0,0];
var globalwithoffset = [event.pageX - bcrOffset.left - offset[0], event.pageY - bcrOffset.top - offset[1]];
local(model.state, globalwithoffset, model.anchor);
debugPoint([event.pageX, event.pageY], 1, 'red');
mousedownelement = element;
requestAnimationFrame(step);
};
var eventhandlertouchend = function(event) {
// clear
model.anchor = false;
requestAnimationFrame(step);
};
element.addEventListener('touchstart', eventhandlertouchstart, false);
element.addEventListener('mousedown', eventhandlermousedown, false);
element.addEventListener('touchend', eventhandlertouchend, false);
elements_tracked.push(element);
// assign some favorable properties to grabbable element.
element.style.webkitTouchCallout = 'none';
element.style.webkitUserSelect = 'none';
// TODO: figure out the proper values for these
element.style.MozUserSelect = 'none';
element.style.msUserSelect = 'none';
element.style.MsUserSelect = 'none';
}
document.addEventListener('mouseup', function() {
if (mousedownelement) {
mousedownelement.__GRAB__.anchor = false;
mousedownelement = false;
requestAnimationFrame(step);
}
}, false);
function GRAB_remove(element, cleartransform) {}
// unimpld
function GRAB_remove_all(cleartransform) {}
GRAB($('#content2')[0]);
(function() {
var requestAnimationFrame = window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.requestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();
var now = function() { return window.performance ? performance.now() : Date.now(); };
var lasttime = 0;
var abs = Math.abs;
var dt = 0;
var scratch0 = [0,0];
var scratch1 = [0,0]; // memory pool
var step = function(time) {
dt = (time - lasttime) * 0.001;
if (time < 1e12) {
// highres timer
} else {
// ms since unix epoch
if (dt > 1e9) {
dt = 0;
}
}
// console.log('dt: ' + dt);
lasttime = time;
var foundnotstopped = false;
for (var i = 0; i < elements_tracked.length; ++i) {
var e = elements_tracked[i];
var data = e.__GRAB__;
if (data.anchor) {
global(data.state, data.anchor, scratch0);
scratch1[0] = scratch0[0] + data.offset[0];
scratch1[1] = scratch0[1] + data.offset[1];
//console.log("output of global", point);
debugPoint(scratch1,
0, 'blue', data.pageoffset);
} else {
scratch1[0] = -1000;
scratch1[1] = -1000;
debugPoint(scratch1, 0, 'blue');
}
// timestep is dynamic and based on reported time. clamped to 100ms.
if (dt > 0.3) {
//console.log('clamped from ' + dt + ' @' + now());
dt = 0.3;
}
vel_verlet_3(data.state, acc, dt);
e.style.webkitTransform = 'translate3d(' + data.state[0] + 'px,' + data.state[1] + 'px,0)' +
'rotateZ(' + data.state[2] + 'rad)';
}
requestAnimationFrame(step);
};
requestAnimationFrame(step);
这基本上会注销调用我的rAF例程(step()
函数)的所有时间
当它正常运行时,它大约每16.7毫秒记录一次时间
我明白了:
这清楚地表明它正在使用相同的时间输入参数运行step()
至少22次,就像时间线试图告诉我的那样
所以我敢说,互联网,你敢告诉我这是故意的行为。:) 我为创建了动画,还创建了requestAnimationFrame()一致性检查器 支持将requestAnimationFrame()自动同步到计算机显示器刷新率(即使不是60Hz)的web浏览器列表列在。。。这意味着在75Hz的监视器上,如果网页当前位于前台,并且CPU/图形性能允许,则requestAnimationFrame()现在在受支持的浏览器上每秒调用75次
- Chrome 30的某个版本有一个令人讨厌的requestAnimationFrame()错误:
- 而且Chrome32Beta似乎正在(再次)制造一些动画流动性缺陷。
此外,我还注意到电源管理(CPU减速/节流太过节省电池电量)会严重影响requestAnimationFrame()的回调速率。。。它表现为在帧渲染时间中向上/向下出现奇怪的尖峰()我认为您有问题,因为您调用了
requestAnimationFrame(步骤)每次mousedown
和mouseup
事件上的code>。因为您的step()
函数也(应该)调用requestAnimationFrame(步骤)
您基本上会为每个mousedown
和mouseup
事件启动新的“动画循环”,因为您从未停止它们,所以它们会累积
我可以看到,您还可以在代码末尾启动“动画循环”。如果要在鼠标事件发生时立即重画,应将绘图移出step()
函数,并直接从鼠标事件处理程序调用该函数
就像这样:
function redraw() {
// drawing logic
}
function onmousedown() {
// ...
redraw()
}
function onmouseup() {
// ...
redraw()
}
function step() {
redraw();
requestAnimationFrame(step);
}
requestAnimationFrame(step);
+但是我觉得如果问题的长度稍微长一点,人们会对它更感兴趣shorter@Onaseriousnote我接受了一些建议,这可能很有意思:我不认为这与每次刷新时运行rAF回调多次的完全错误行为有什么关系。无论如何,在rAF像setTimeout一样防弹之前,似乎还有很多工作要做。是的,您的伪代码示例是管理rAF渲染循环正确方法的一个很好的升华,事实上,通过鼠标单击启动额外的渲染“线程”是错误的,它会导致一种很难解决的情况。。。我需要重新审视这段代码,并找出这是否是我遇到的问题中的一个重要因素。
window.rafbuf = [];
var step = function(time) {
window.rafbuf.push(time);
function redraw() {
// drawing logic
}
function onmousedown() {
// ...
redraw()
}
function onmouseup() {
// ...
redraw()
}
function step() {
redraw();
requestAnimationFrame(step);
}
requestAnimationFrame(step);