6.2.2_图像绘制器
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图像绘制器</title>
<style>
body{
background: #ddd;
}
#canvas{
background: #fff;
cursor: pointer;
margin: 10px;
-webkit-box-shadow: 3px 3px 6px rgba(0,0,0,0.5);
-moz-box-shadow: 3px 3px 6px rgba(0,0,0,0.5);
box-shadow: 3px 3px 6px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="300"></canvas>
</body>
<script>
var Sprite = function(name,painter,behaviors){
if(name !== undefined){ this.name = name; }
if(painter !== undefined){ this.painter = painter; }
this.top = 0;
this.left = 0;
this.width = 10;
this.height = 10;
this.velocityX = 0;
this.velocityY = 0;
this.visible = true;
this.animating = false;
this.behaviors = behaviors || [];
}
Sprite.prototype = {
paint:function(context){
if(this.painter !== undefined && this.visible){
this.painter.paint(this,context);
}
},
update:function(context,time){
for(var i=0;i<this.behaviors.length;i++){
this.behaviors[i].execute(this,context,time);
}
}
}
</script>
<script>
var ImagePainter = function (imageUrl){
this.image = new Image();
this.image.src = imageUrl;
}
ImagePainter.prototype ={
paint:function(sprite,context){
if(this.image.complete){
context.drawImage(this.image,sprite.left,sprite.top,sprite.width,sprite.height);
}
}
}
</script>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var tree = new Sprite('tree', new ImagePainter('img/small_tree.png'));
tree.left = 220;
tree.top = 80;
tree.width = 140;
tree.height = 150;
window.requestAnimationFrame(animate);
function animate(){
context.clearRect(0,0,canvas.width,canvas.height);
tree.paint(context);
window.requestAnimationFrame(animate);
console.log('动画持续中');
}
</script>
</html>
![这里写图片描述](https://img-blog.csdn.net/20170527133537416?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvanVuX3N1bl9zaGluZQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)