Canvas实现曲线运动

时间:2025-04-01 21:37:45
  • 前言

Html5添加的最受欢迎的功能就是<canvas>元素,它负责在页面中设定一个区域,然后在里面可以通过javascript动态地在其内绘制图形。

主流浏览器,IE9+,手机端都是支持它的。

  • 创建Canvas

要使用Canvas元素就必须先设置其width和height,指定绘图区域的大小

类似:<canvas id="canvas" width="800" height="800"/>

如果要在这块画布上绘图的话,首先要取得绘图上下文,需调用getContext()方法

var canvas=document.getElementById("canvas");

//判断浏览器是否支持canvas

if(canvas.getContext)

{   var draw=canvas.getContext("2d");//这里2d  取得2d上线文对象,还有一个WebGL的3D上下文(还未接触过,不在此陈诉了)

}

我们用2d上下文可以绘制简单的2d图形,如矩形,弧线。

  • 利用Canvas创建曲线运动

这里有个demo是曲线运动,直接上代码

 <!DOCTYPE html>
<html>
<head>
<meta charset=gbf>
<title>曲线运动</title>
<script>
//box
var box_x=0;
var box_y=0;
var box_width=500;
var box_height=500;
//ball
var ball_x=10;
var ball_y=10;
var ball_radius=10;
var ball_vx=10;
var ball_vy=0;
//constant
var g=10;//note
var rate=0.9;
//bound
var bound_left=box_x+ball_radius;
var bound_right=box_x+box_width-ball_radius;
var bound_top=box_y+ball_radius;
var bound_bottom=box_y+box_height-ball_radius;
//context
var ctx;
function init()
{
ctx=document.getElementById('canvas').getContext('2d');
//
ctx.lineWidth=ball_radius;
//设置球的颜色
ctx.fillStyle="rgb(200,0,50)";
move_ball();
setInterval(move_ball,100);
} function move_ball()
{
//清除画布上的矩形区域
ctx.clearRect(box_x,box_y,box_width,box_height);
move_and_check();
//开始曲线路径
ctx.beginPath();
//绘制圆球
ctx.arc(ball_x,ball_y,ball_radius,0,Math.PI*2,true);
//fillstyle填充
ctx.fill();
//绘制指定矩形
ctx.strokeRect(box_x,box_y,box_width,box_height);
} function move_and_check()
{
var cur_ball_x=ball_x+ball_vx;
var temp=ball_vy;
ball_vy=ball_vy+g;
var cur_ball_y=ball_y+ball_vy+g/2;
if(cur_ball_x<bound_left)
{
cur_ball_x=bound_left;
ball_vx=-ball_vx*0.9;
ball_vy=ball_vy*0.9;
}
if(cur_ball_x>bound_right)
{
cur_ball_x=bound_right;
ball_vx=-ball_vx*0.9;
ball_vy=ball_vy*0.9;
}
if(cur_ball_y<bound_top)
{
cur_ball_y=bound_top;
ball_vy=-ball_vy*0.9;
ball_vx=ball_vx*0.9;
}
if(cur_ball_y>bound_bottom)
{
cur_ball_y=bound_bottom;
ball_vy=-ball_vy*0.9;
ball_vx=ball_vx*0.9;
}
ball_x=cur_ball_x;
ball_y=cur_ball_y;
}
</script>
</head>
<body onLoad="init()">
<canvas id="canvas" width="800" height="800"/>
</body>
</html>

代码中包含了少部分2D上下文API。详细API请参考:

http://www.w3school.com.cn/html5/html_5_canvas.asp;

http://blog.teamtreehouse.com/getting-started-with-the-canvas-api

http://javascript.ruanyifeng.com/htmlapi/canvas.html

  • 最后

很多css3不能表现的复杂动画,通过canvas,js来配合解决是极好的,当然这里面还有很多东西,这里小小记录下canvas的一下基本用法。