Skip to content

Instantly share code, notes, and snippets.

@bydmm
Last active May 26, 2017 03:33
Show Gist options
  • Save bydmm/94cdbb15a002cf5a8f30116e4be0a86b to your computer and use it in GitHub Desktop.
Save bydmm/94cdbb15a002cf5a8f30116e4be0a86b to your computer and use it in GitHub Desktop.
Quantum Cloud
<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<title>Quantum Cloud</title>
<style>
header {
text-align: center;
}
.canvas-container {
display: block;
padding: 0;
width: 500px;
margin: 0 auto;
}
.frame {
text-align: center;
}
</style>
</head>
<body>
<div class="canvas-container">
<canvas id="js-canvas" class="canvas" width="500" height="500"></canvas>
<div class="frame" id="js-frame"></div>
</div>
<script type="text/javascript">
var QuantumCloud = {
frame: 0,
canvas: document.getElementById("js-canvas"),
now: function() {
var d = new Date();
return d.getTime() / 1000;
},
monteCarlo: function() {
var r = Math.sqrt(-2.0 * Math.log(Math.random()));
var theta = 2.0 * Math.PI * Math.random();
var point = {
x: r * Math.cos(theta),
y: r * Math.sin(theta)
}
return point;
},
canvasContext: function() {
if (this.canvas.getContext) {
return this.canvas.getContext("2d");
} else {
throw 'Could not get Canvas context';
}
},
drawElectron: function(x, y, radius) {
var ctx = this.canvasContext();
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI*2, true);
ctx.fillStyle = 'rgba(0, 0, 0, 0.01)';
ctx.fill();
},
draw: function() {
var point = this.monteCarlo();
var centerX = this.canvas.offsetWidth / 2;
var centerY = this.canvas.offsetHeight / 2;
var x = centerX + (centerX * point.x) / 4;
var y = centerY + (centerY * point.y) / 4;
this.drawElectron(x, y , 1);
},
animloop: function() {
if(this.frame > this.frameLimit) return;
this.frame++;
this.animloop();
this.draw();
},
showFrame: function() {
var frameDom = document.getElementById("js-frame");
var cost = this.now() - this.start;
frameDom.innerText = 'Frame: ' + this.frame + ' Cost: ' + cost;
},
run: function(frameLimit) {
this.start = this.now();
for (var i = 0; i < frameLimit; i++) {
this.frame++;
this.draw();
}
this.showFrame();
}
}
QuantumCloud.run(1000000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment