var canvas = document.getElementById('canvas');
//获取canvas元素
var context = canvas.getContext('2d');
//返回一个用于在画布上绘图的环境 环境内有函数
var radius = 20;//半径
var color = "#0000ff";
var g = 1;//重力加速度
var x = 0;//初始位置
var y = 50;
var vx = 1;//初始速度
var vy = 0.1;
window.onload = init();//首先执行该函数
function init(){
setInterval(onEachStap,10);// 60帧 10ms更新一次
};
function onEachStap(){
vy += g;
x += vx;
y += vy;
if(y > canvas.height - radius){//触底反弹
y = canvas.height - radius;
vy = -vy;
}
if(x > canvas.width + radius){//防止出界
x = 50;
}
drawBall();//绘制小球
};
function drawBall(){
with(context){
clearRect(0,0,canvas.width,canvas.height);
fillStyle = color;
beginPath();
arc(x,y,radius,0,2*Math.PI,true);
closePath();
fill();
};
};
- window.onload()方法用于在网页加载完毕后立刻执行的操作
- 常用于《body》元素,在也买你载入后执行脚本代码
- 只有一个待执行函数
- Window.onload = 函数;
- 有多个待执行函数
- Window.onload = function(){
- Func1();
- Func2();
- …
- }
- 页面加载完依次执行1,2,…
- Window.onload = function(){
- 用处
- 等DOM树生成后执行js,可防止“undefined”ERROR
- 可以绑定匿名函数,也可绑定具体函数
- 拓展:
- window.onload = function () {}; // JavaScript
$(document).ready(function () {}); // jQuery - 有什么区别?功能相同
- window.onload = function () {}; // JavaScript
- HTMLCanvasElement.getContext(contextID)
- 返回一个在画布上绘图的环境,目前只支持2d(把contextID参数替换为“2d”)
- 除了这个参数还有其它内容
- HTMLCanvasElement.getContext() - Web API 接口参考 | MDN (mozilla.org)
- 使用控制台输出可得,返回的内容包含内置函数
- With