Scissor animation
io error: No such file or directory (os error 2) (/home/runner/work/yari/yari/mdn/content/files/en-us/learn/webgl/by_example/raining_rectangles/index.md)
使用剪切和清除操作实现一些动画的简单 WebGL 的例子。
剪切动画
本例中,我们使用scissor()
和 clear()
。我们再次建立一个动画循环使用计时器。注意,这次是方块的位置 (剪切区) 更新每一帧 (我们设置帧率大约每 17 毫秒,约 60 fps -帧每秒)
相比之下,方块的颜色 (用clearColor
) 仅创建一个新的方块。这是一个很好的演示WebGL是一个状态机。对于每一个方块,我们设置它的颜色,然后只更新它的位置每一帧。WebGL 的清晰的颜色状态维持在设定值,直到我们再次改变它创建一个新的方块。
js
"use strict";
window.addEventListener("load", setupAnimation, false);
// Variables to hold the WebGL context, and the color and
// position of animated squares.
var gl,
color = getRandomColor(),
position;
function setupAnimation(evt) {
window.removeEventListener(evt.type, setupAnimation, false);
if (!(gl = getRenderingContext())) return;
gl.enable(gl.SCISSOR_TEST);
gl.clearColor(color[0], color[1], color[2], 1.0);
// Unlike the browser window, vertical position in WebGL is
// measured from bottom to top. In here we set the initial
// position of the square to be at the top left corner of the
// drawing buffer.
position = [0, gl.drawingBufferHeight];
var button = document.querySelector("button");
var timer;
function startAnimation(evt) {
button.removeEventListener(evt.type, startAnimation, false);
button.addEventListener("click", stopAnimation, false);
document.querySelector("strong").innerHTML = "stop";
timer = setInterval(drawAnimation, 17);
drawAnimation();
}
function stopAnimation(evt) {
button.removeEventListener(evt.type, stopAnimation, false);
button.addEventListener("click", startAnimation, false);
document.querySelector("strong").innerHTML = "start";
clearInterval(timer);
}
stopAnimation({ type: "click" });
}
// Variables to hold the size and velocity of the square.
var size = [60, 60],
velocity = 3.0;
function drawAnimation() {
gl.scissor(position[0], position[1], size[0], size[1]);
gl.clear(gl.COLOR_BUFFER_BIT);
// Every frame the vertical position of the square is
// decreased, to create the illusion of movement.
position[1] -= velocity;
// When the sqaure hits the bottom of the drawing buffer,
// we override it with new square of different color and
// velocity.
if (position[1] < 0) {
// Horizontal position chosen randomly, and vertical
// position at the top of the drawing buffer.
position = [
Math.random() * (gl.drawingBufferWidth - size[0]),
gl.drawingBufferHeight,
];
// Random velocity between 1.0 and 7.0
velocity = 1.0 + 6.0 * Math.random();
color = getRandomColor();
gl.clearColor(color[0], color[1], color[2], 1.0);
}
}
function getRandomColor() {
return [Math.random(), Math.random(), Math.random()];
}
The source code of this example is also available on GitHub.
io error: No such file or directory (os error 2) (/home/runner/work/yari/yari/mdn/content/files/en-us/learn/webgl/by_example/raining_rectangles/index.md)