好的。我需要画布首先加载js,但js需要首先加载canvas。下面的代码:HTML需要js和canvas彼此加载
height="400" id="myCanvas" style="border: 1px solid; border-color:
#000000">
而我的JS:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
function gen_line(point1, point2) {
var x = point1.x;
var y = point1.y;
var z = point1.z;
var x2 = point2.x;
var y2 = point2.y;
var z2 = point2.z;
var points = [];
if (x === x2) {
// manual array gen
} else {
var slope = (z - z2)/(x - x2);
if (slope < 0) {
x = point2.x;
y = point2.y;
z = point2.z;
x2 = point1.x;
y2 = point1.y;
z2 = point1.z;
var slope = (z - z2)/(x - x2);
console.log("hi");
}
if (slope <= 1) {
var z_intercept = z - slope * x;
for (var x = x + 1; x < x2; x++) {
points.push(new Point(x, 0, x * slope + z_intercept));
}
} else {
slope = (x - x2)/(z - z2);
var x_intercept = x - slope * z;
for (var z = z + 1; z < z2; z++) {
points.push(new Point(z * slope + x_intercept, 0, z));
}
}
}
return points;
}
var Face = function (a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
Face.prototype.generate = function() {
return this.get_lines().concat(this.get_points());
};
Face.prototype.get_lines = function() {
var v = this.get_points();
var points = gen_line(v[0], v[1]);
return points;
};
Face.prototype.get_points = function() {
return [this.a, this.b, this.c]
};
Face.prototype.draw = function() {
var v = this.generate();
for (var i = 0; i < v.length; i++) {
v[i].draw();
}
};
var Point = function (x, y, z) {
this.x = Math.round(x);
this.y = Math.round(y);
this.z = Math.round(z);
}
Point.prototype.draw = function() {
ctx.fillStyle = "#FF0000";
ctx.fillRect(this.x * 20, this.z * 20, 20, 20);
};
var faces = [new Face(new Point(5, 0, 2), new Point(2, 0, 5), new
Point(1, 0, 10))];
function update_loc(event) {
faces = [new Face(new Point(Math.round(event.clientX/20), 0,
Math.round(event.clientY/20), new Point(2, 0, 5), new Point(1, 0,
10))]
}
setInterval(onTimerTick, 33); // 33 milliseconds = ~ 30 frames per sec
function onTimerTick() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
faces[0].draw();
ctx.beginPath();
for (var i = 1; i < 20; i++) {
ctx.moveTo(0, i * 20);
ctx.lineTo(400, i * 20);
}
for (var i = 1; i < 20; i++) {
ctx.moveTo(i * 20, 0);
ctx.lineTo(i * 20, 400);
}
ctx.stroke();
}
你应该专注于代码是在底部。其余的我不认为重要,但是我会去那里,以防万一。如果您有任何关于如何解决此问题的建议,请回复。谢谢!
+0
你可以发布你的js文件代码吗? –
+1
这里的问题是**为什么**你想要这个吗?我注意到你有一个'onmousemove'属性。你可以通过删除这个属性来解决这个竞争条件,并从**你的JS文件中监听事件**:为了使事情正常工作,依赖于代码的代码通常需要等待页面完成加载。我会建议离开它的JS调用,并绑定从你的脚本''onmousemove'事件**:'window.onload = function(){this.addEventListener('mousemove',update_loc)}' –