问题描述
|
我想知道我的代码有什么问题(为什么动画这么生涩):
<html>
<head>
</head>
<body style=\"background:black;margin:0;padding:0;\">
<canvas id=\"canvas\" style=\"background:white;width:100%;height:100%;\"/>
<script>
var img=new Image();
img.onload=function(){
var c=document.getElementById(\'canvas\');
var ctx = c.getContext(\'2d\');
var left,top;
left=top=0;
ctx.drawImage(img,left,top,20,20);
var f=function(){
left+=1;
top+=1;
c.width=c.width;
ctx.drawImage(img,20);
};
setInterval(f,20);
};
img.src=\"http://a.wearehugh.com/dih5/aoc-h.png\";
</script>
</body>
</html>
据我所知,帆布应该擅长于做这些事情?但是,如果我改为使用一个元素并操纵其左侧和顶部,则最终会变得更快(减少抖动)。
我的脚本有问题吗?还是这是最好的画布?
解决方法
无需在每次迭代时清除整个画布。可以使用
clearRect
方法。
每次绘制图像时,都必须缩放图像。为避免这种情况,您只能在不可见的画布上绘制一次,然后在可见的画布上绘制。
具有提高的可读性和性能的代码:
<html>
<head>
</head>
<body style=\"background:black;margin:0;padding:0;\">
<canvas id=\"canvas\" style=\"background:white;width:100%;height:100%;\"/>
<script>
var img=new Image()
buf = document.createElement(\'canvas\');
img.onload=function(){
var c = document.getElementById(\'canvas\'),ctx = c.getContext(\'2d\'),left = 0,top = 0,width = 20,height = 20;
buf.width = width;
buf.height = height;
buf.getContext(\'2d\').drawImage(img,width,height);
var f=function(){
ctx.clearRect(left-1,top-1,width + 1,height + 1)
left+=1;
top+=1;
ctx.drawImage(buf,left,top,height);
};
setInterval(f,20);
};
img.src=\"http://a.wearehugh.com/dih5/aoc-h.png\";
</script>
</body>
</html>