确定。我需要画布首先加载js,但js需要首先加载画布。这是代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<center><canvas onmousemove="update_loc(event)" width="400"
height="400" id="myCanvas" style="border: 1px solid; border-color:
#000000"></canvas></center>
<script src="./js.js"></script>
</body>
</html>
我的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 :(得分:1)
要替换的是此部分以打破循环依赖
onmousemove="update_loc(event)"
你可以通过从JS添加事件监听器而不是像这样的
来实现document.getElementById('myCanvas').onmousemove = update_loc
理想情况下,在页面加载时。