canvas动画制作
程序员文章站
2022-03-09 20:46:56
...
绘制图片
- drawImage()
- 三个参数drawImage(img,x,y)
- img 图片对象、canvas对象、video对象
- x,y 图片绘制的左上角
- 五个参数drawImage(img,x,y,w,h)
- img 图片对象、canvas对象、video对象
- x,y 图片绘制的左上角
- w,h 图片绘制尺寸设置(图片缩放,不是截取)
- 九个参数drawImage(img,x,y,w,h,x1,y1,w1,h1)
- img 图片对象、canvas对象、video对象
- x,y,w,h 图片中的一个矩形区域
- x1,y1,w1,h1 画布中的一个矩形区域
- 三个参数drawImage(img,x,y)
坐标变换
- 平移 移动画布的原点
- translate(x,y) 参数表示移动目标点的坐标
- 缩放
- scale(x,y) 参数表示宽高的缩放比例
- 旋转
- rotate(angle) 参数表示旋转角度
案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>lmy</title>
</head>
<body>
<canvas width="600" height="400" style="border: 1px solid #ccc"></canvas>
<script type="text/javascript">
function Person(){
this.ctx=document.querySelector('canvas').getContext('2d');
this.src="03.png";
this.w=this.ctx.canvas.width;
this.h=this.ctx.canvas.height;
this.stepSize=10;
this.stepX=0;
this.stepY=0;
this.index=0;
this.derection=0;
}
Person.prototype.init=function(){
this.loadImage()
}
Person.prototype.loadImage=function(){
var image=new Image();
image.onload=function(){
this.imageW=image.width;
this.imageH=image.height;
//人物
this.personW=this.imageW/4;
this.personH=this.imageH/4;
//起点
this.x0=this.w/2-this.personW/2;
this.y0=this.h/2-this.personH/2;
//绘制
this.ctx.drawImage(image,0,0,this.personW,this.personH,this.x0,this.y0,this.personW,this.personH);
this.move(image);
}.bind(this)
image.src=this.src;
}
//方向键
Person.prototype.move=function(image){
document.onkeydown=function(e){
switch(e.keyCode){
case 37:
this.derection=1;
this.stepX--;
if(this.stepX<=-28){
this.stepX=-28;
console.log(this.stepY)
}
this.drawImage(image)
break;
case 38:
this.derection=3;
this.stepY--;
if(this.stepY<=-17){
this.stepY=-17;
console.log(this.stepY)
}
this.drawImage(image)
break;
case 39:
this.derection=2;
this.stepX++;
if(this.stepX>=+28){
this.stepX=28;
console.log(this.stepY)
}
this.drawImage(image)
break;
case 40:
this.derection=0;
this.stepY++;
if(this.stepY>=17){
this.stepY=17;
console.log(this.stepY)
}
this.drawImage(image)
break;
}
}.bind(this)
}
Person.prototype.drawImage=function(image){
this.index++;
this.ctx.clearRect(0,0,this.w,this.h)
this.ctx.drawImage(image,
this.index*this.personW,this.derection*this.personH,
this.personW,this.personH,
this.x0+this.stepX*this.stepSize,this.y0+this.stepY*this.stepSize,
this.personW,this.personH
)
if(this.index>=3){
this.index=-1;
}
}
var person=new Person();
person.init();
</script>
</body>
</html>