标签:back har int 距离 alt 上下 function val charset
一、引言
本文主要是canvas绘图中绘制图像的部分,做了几个练习,综合起来,复习canvas绘图以及定时器的使用。
二、canvas绘制小飞机在指定位置
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>小飞机静止位于上下左右中</title>
<style>
body{
text-align:center;
}
canvas{
background:#f0f0f0;
}
</style>
</head>
<body>
<canvas id="c7" width="500" height="400">
您的浏览器不支持canvas标签!
</canvas>
<script>
var ctx = c7.getContext(‘2d‘);
var p2 = new Image();
p2.src = ‘image/p2.png‘;
console.log(p2.width);
p2.onload = function(){
ctx.drawImage(p2,0,0);
ctx.drawImage(p2,500-p2.width,0);
ctx.drawImage(p2,0,400-p2.height);
ctx.drawImage(p2,500-p2.width,400-p2.height);
ctx.drawImage(p2,250-200,200-100,400,200);
}
</script>
</body>
</html>
实现效果:
三、canvas绘制小飞机左右自动移动
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>左右移动的小飞机</title>
<style>
body{
text-align:center;
}
canvas{
background:#f0f0f0;
}
</style>
</head>
<body>
<canvas id="c7" width="500" height="400">
您的浏览器不支持canvas标签!
</canvas>
<script>
var ctx = c7.getContext(‘2d‘);
var p3 = new Image();
p3.src = ‘image/p3.png‘;
console.log(p3.width);
p3.onload = function(){
var x = 0;
var xDirection = 1;
var y = 0;
setInterval(function(){
//清除画布上已有的内容
ctx.clearRect(0,0,500,400);
ctx.drawImage(p3,x,y);
x += 5*xDirection;
if(x>=500-p3.width){
xDirection = -1;
}
if(x<0){
xDirection = 1;
}
},30);
}
</script>
</body>
</html>
四、canvas绘制随鼠标移动的小飞机
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>随鼠标移动的小飞机</title>
<style>
body{
text-align:center;
}
canvas{
background:#f0f0f0;
}
</style>
</head>
<body>
<canvas id="c7" width="500" height="400">
您的浏览器不支持canvas标签!
</canvas>
<script>
var ctx = c7.getContext(‘2d‘);
var p3 = new Image();
p3.src = ‘image/p3.png‘;
console.log(p3.width);
p3.onload = function(){
var x = 0;
var y = 0;
//监听鼠标在画布上方移动事件
c7.onmousemove= function(e){
x = e.offsetX;
y = e.offsetY;
};
//使用定时器,不停的清画布,重绘飞机
//小坑:飞机的定位点是左上角,要改变定位点距离,改变重绘的x.y
setInterval(function(){
ctx.clearRect(0,0,500,400);
ctx.drawImage(p3,x-p3.width/2,y-p3.height/2);
},20);
}
</script>
</body>
</html>
标签:back har int 距离 alt 上下 function val charset
原文地址:http://www.cnblogs.com/ljq66/p/7617826.html