我有一个简单的javascript程序。
您可以在其中移动一个正方形。
但是过了一会儿,它开始变慢和滞后。
出什么问题了?为什么这么慢?
使用ram是否过多?
我使用Javascript canvas和setInterval。 还是真的过时了?
aaaaaaaaaaaaaaaaaaaa
对不起,我的英语说得不好。
<body onload="Start()">
<script>
function Start() {
myAvatar = new component("black", 30, 30, 50, 50);
goldMine = new component("yellow", 30, 30, 200, 100),
Field.start();
}
var Field = {
field: document.createElement("canvas"),
start: function () {
this.field.height = 800;
this.field.width = 800;
this.context = this.field.getContext("2d");
document.body.insertBefore(this.field, document.body.childNodes[0]);
this.interval = setInterval(fieldUpdate, 10);
window.addEventListener('keydown', function (e) {
Field.keys = Field.keys || [];
Field.keys[e.keyCode] = (e.type == "keydown");
})
/////KEY UP/////
window.addEventListener('keyup', function (e) {
Field.keys[e.keyCode] = (e.type == "keydown");
})
},
clear: function () {
this.context.clearRect(0, 0, this.field.width, this.field.height);
}
}
function component(color, width, height, x, y) {
this.color = color;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.componentUpdate = function () {
ctx = Field.context;
ctx.save();
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
function fieldUpdate() {
Field.clear();
myAvatar.componentUpdate();
goldMine.componentUpdate();
if (Field.keys && Field.keys[37]) {
myAvatar.x--;
var origCoord = [myAvatar.x, myAvatar.y];
}
if (Field.keys && Field.keys[38]) {
myAvatar.y--;
var origCoord = [myAvatar.x, myAvatar.y];
}
if (Field.keys && Field.keys[39]) {
myAvatar.x++;
var origCoord = [myAvatar.x, myAvatar.y];
}
if (Field.keys && Field.keys[40]) {
myAvatar.y++;
var origCoord = [myAvatar.x, myAvatar.y];
}
}
</script>
</body>