Advertisement
here2share

# js_starfield_demo.py

Nov 25th, 2019
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. # js_starfield_demo.py
  2.  
  3. import tempfile
  4. import webbrowser
  5. import os
  6.  
  7. js_data = '''<!DOCTYPE html5>
  8. <html>
  9. <head>
  10.  <title>3D Starfield in HTML5 Canvas</title>
  11.  
  12.  <script type='text/javascript'>
  13.    MAX_DEPTH = 32;
  14.  
  15.    var canvas, ctx;
  16.    var stars = new Array(512);
  17.  
  18.    window.onload = function() {
  19.      canvas = document.getElementById("tutorial");
  20.      if( canvas && canvas.getContext ) {
  21.        ctx = canvas.getContext("2d");
  22.        initStars();
  23.        setInterval(loop,33);
  24.       }
  25.    }
  26.  
  27.    /* Returns a random number in the range [minVal,maxVal] */
  28.    function randomRange(minVal,maxVal) {
  29.      return Math.floor(Math.random() * (maxVal - minVal - 1)) + minVal;
  30.    }
  31.  
  32.    function initStars() {
  33.      for( var i = 0; i < stars.length; i++ ) {
  34.        stars[i] = {
  35.          x: randomRange(-25,25),
  36.          y: randomRange(-25,25),
  37.          z: randomRange(1,MAX_DEPTH)
  38.         }
  39.      }
  40.    }
  41.  
  42.    function loop() {
  43.      var halfWidth  = canvas.width / 2;
  44.      var halfHeight = canvas.height / 2;
  45.  
  46.      ctx.fillStyle = "rgb(0,0,0)";
  47.      ctx.fillRect(0,0,canvas.width,canvas.height);
  48.  
  49.      for( var i = 0; i < stars.length; i++ ) {
  50.        stars[i].z -= 0.2;
  51.  
  52.        if( stars[i].z <= 0 ) {
  53.          stars[i].x = randomRange(-25,25);
  54.          stars[i].y = randomRange(-25,25);
  55.          stars[i].z = MAX_DEPTH;
  56.        }
  57.  
  58.        var k  = 128.0 / stars[i].z;
  59.        var px = stars[i].x * k + halfWidth;
  60.        var py = stars[i].y * k + halfHeight;
  61.  
  62.        if( px >= 0 && px <= 500 && py >= 0 && py <= 400 ) {
  63.          var size = (1 - stars[i].z / 32.0) * 5;
  64.          var shade = parseInt((1 - stars[i].z / 32.0) * 255);
  65.          ctx.fillStyle = "rgb(" + shade + "," + shade + "," + shade + ")";
  66.          ctx.fillRect(px,py,size,size);
  67.        }
  68.      }
  69.    }
  70.  </script>
  71.  
  72. <body>
  73.  <canvas id='tutorial' width='500' height='400'>
  74.    Your browser does not support HTML5 canvas.
  75.    Please upgrade your browser.
  76.  </canvas>
  77. </body>
  78. </html>
  79. '''
  80.  
  81. '''
  82. '''
  83.  
  84. chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
  85.  
  86. tf = tempfile.mktemp(".html", "JSdemo_")
  87. print tf
  88. with open(tf, 'w') as temp:
  89.     temp.write(js_data)
  90. webbrowser.get(chrome_path).open(tf)
  91. os.remove(tf)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement