利用canvas来绘制一个会动的图画,欢迎指教

来源:转载

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绘制小人动画</title>
<style>
canvas{
border: 1px solid green;
}
</style>
</head>
<body>
<!-- 绘制小人动画 -->
<canvas width="400" height="600" id="canvas"></canvas>
</body>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function toAngle(radian){
return radian*180/Math.PI;
}
function toRadian(angle){
return angle*Math.PI/180;
}
function img(ctx,element,x0,y0){
var x = x0,
y = y0;
element.onload = function(){
var width = element.width/4,
height = element.height/4;
var i = 0,
j = 0,
a = 0;
setInterval(function(){
//x = x + a;
ctx.clearRect(x,y,width,height);
ctx.drawImage(element,width*i,height*j,width,height,x,y,width,height);
i ++;
if(i == 4){
setTimeout(function(){
i = 0;
if(j == 0){
j =1;
//a-=10;
}else if(j == 1){
j = 3;
}else if(j == 2){
j = 0;
}else if(j == 3){
j = 2;
//a+=10;
}
},20)
}
},200)
}
};
var img1 = new Image();
img1.src = 'imgs/game1.png';
img(ctx,img1,0,0);

//这边是自己封装了一个函数,其实从性能优化的角度来考虑,我们可以先在内存中创建一个canvas标签,将这个图画放在内存中的canvas里面,再将内存中创建好的canvas放到页面上的这个canvas标签上,这只是一个思路,希望大家可以往这方面考虑
</script>
</html>

分享给朋友:
您可能感兴趣的文章:
随机阅读: