Skip to content

Instantly share code, notes, and snippets.

@st3b1t
Created July 4, 2023 14:38
Show Gist options
  • Save st3b1t/c4428132848a507030daa8254b4a532d to your computer and use it in GitHub Desktop.
Save st3b1t/c4428132848a507030daa8254b4a532d to your computer and use it in GitHub Desktop.
Math.random() vs crypto.getRandomValues() Visual random generation values from different ways in Javascript
<html>
<head>
<title>Math.random() vs crypto.getRandomValues()</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
body { background: #333; text-align: center; }
canvas {
margin: 50px;
height: 400px;
width: 400px;
background: black;
border: 1px solid black;
}
button {
text-align: center;
font-size: 24px
}
table {
color: #eee;
}
</style>
</head>
<body>
<table>
<tr>
<td colspan="2" style="text-align: center;">
<button>Generate</button>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
Visual random generation values from different ways in Javascript
</td>
</tr>
<tr>
<td>Math.random()</td>
<td>crypto.getRandomValues()</td>
</tr>
<tr>
<td>
<canvas id="c1"></canvas>
</td>
<td>
<canvas id="c2"></canvas>
</td>
</tr>
</table>
<script>
const canvas1 = document.querySelector('#c1')
, canvas2 = document.querySelector('#c2')
, dpi = window.devicePixelRatio;
var size = 400;
function rescale(canvas) {
canvas.width = size * dpi;
canvas.height = size * dpi;
//canvas.style.width = size * dpi + "px";
//canvas.style.height = size * dpi + "px";
}
rescale(canvas1);
rescale(canvas2);
const context1 = canvas1.getContext('2d')
, context2 = canvas2.getContext('2d');
const {width} = canvas1.getBoundingClientRect();
function drawPix(x, y, context) {
context.fillStyle = '#fff';
context.fillRect(x, y, 1, 1);
}
function getRnd(max) {
return Math.floor(Math.random() * max);
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRndCrypt(max) {
// Create byte array and fill with 1 random number
var byteArray = new Uint8Array(1);
crypto.getRandomValues(byteArray);
var range = max + 1;
var max_range = 256;
if (byteArray[0] >= Math.floor(max_range / range) * range)
return getRnd(max);
return (byteArray[0] % range);
}
function clear() {
context1.clearRect(0, 0, width, width);
context2.clearRect(0, 0, width, width);
}
function draw() {
clear();
const maxPix = Math.pow(width, 2);
for (let i=0; i < maxPix; i++) {
drawPix(getRnd(width), getRnd(width), context1)
drawPix(getRndCrypt(width), getRndCrypt(width), context2)
//console.log(getRnd(width), getRndCrypt(width))
}
}
//setInterval(draw, 10)
//draw();
document.querySelector('button').addEventListener('click', draw, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment