我设置了这个简单的 Koch 分形 JSFiddle - http://jsfiddle.net/oana/kU5D8/9/ -
但没有骰子。
代码来自 Keith Peters 的 Playing with Chaos。
该代码在本地工作。在本地,它是这样组织的:HTML 文件明确引用了 2 个 .js 文件。第一个,chaos.js,包含变量 chaos 的赋值。第二个,koch.js,包含分配给 window.onload 的函数表达式。
这对我来说更像是一个 JSFiddle 练习。如何开始调试为什么我在 JSFiddle 中看到 nada?
非常感谢你!
PS:stackoverflow 告诉我到 jsfiddle.net 的链接必须附有代码所以这里是代码 -
var chaos = (function () {
return {
init: function () {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext("2d");
this.setSize(window.innerWidth, window.innerHeight);
},
setSize: function (width, height) {
this.width = this.canvas.width = width;
this.height = this.canvas.height = height;
},
clear: function () {
if (color) {
this.context.fillStyle = color;
this.context.fillRect(0, 0, this.width, this.height);
} else {
this.context.clearRect(0, 0, this.width, this.height);
}
}
};
}());
window.onload = function () {
var maxDepth = 0;
init();
function init() {
chaos.init();
draw();
document.body.addEventListener('keyup',
function (event) {
console.log(event.keyCode);
switch (event.keyCode) {
case 32:
maxDepth += 1;
draw();
break;
default:
break;
}
});
}
function draw() {
var p0 = {
x: chaos.width * 0.1,
y: chaos.height * 0.75
};
var p1 = {
x: chaos.width * 0.9,
y: chaos.height * 0.75
};
chaos.clear();
chaos.context.lineWidth = 2;
koch(p0, p1, maxDepth);
}
function koch(p0, p1, depth) {
var dx = p1.x - p0.x,
dy = p1.y - p0.y,
dist = Math.sqrt(dx * dx + dy * dy),
unit = dist / 3,
angle = Math.atan2(dy, dx), pa, pb, pc;
pa = {
x: p0.x + Math.cos(angle) * unit,
y: p0.y + Math.sin(angle) * unit
};
pb = {
x: pa.x + Math.cos(angle - Math.PI / 3) * unit,
y: pa.y + Math.sin(angle - Math.PI / 3) * unit
};
pc = {
x: p0.x + Math.cos(angle) * unit * 2,
y: p0.y + Math.sin(angle) * unit * 2
};
if (depth === 0) {
chaos.context.beginPath();
chaos.context.moveTo(p0.x, p0.y);
chaos.context.lineTo(pa.x, pa.y);
chaos.context.lineTo(pb.x, pb.y);
chaos.context.lineTo(pc.x, pc.y);
chaos.context.lineTo(p1.x, p1.y);
chaos.context.stroke();
} else {
koch(p0, pa, depth - 1);
koch(pa, pb, depth - 1);
koch(pb, pc, depth - 1);
koch(pc, p1, depth - 1);
}
}
};