The Stack Overflow podcast is back! Listen to an interview with our new CEO.

Hot answers tagged

21

Try using a SVG object on the canvas: <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg"> <defs> <pattern id="smallGrid" width="8" height="8" patternUnits="userSpaceOnUse"> <path d="M 8 0 L 0 0 0 8" fill="none" stroke="gray" stroke-width="0.5" /> </pattern> <pattern id="...


16

Quill already did a good job speeding up your code, so I'll focus on the code you have right now. Give me the object! (Not how to get it) Your drawGrid function takes the id of a DOM element that the function is expected to find on its own. However, this is not good practice. Instead, you should pass the DOM element itself. This could also speed up your ...


16

You're rendering the same line too many times. To create the grid you need to draw (w/stepSize) vertical lines and (h/stepSize) horizontal lines. Total: (w+h)/stepSize lines You used two nested loops, and you drew: (w/stepSize)*(h/stepSize) = (w * h)/(stepSize * stepSize) lines To give you a perspective few examples: For w=1000, h=1000, stepSize=20. ...


14

Some thoughts on your general code style (some points might depend on personal preference): I suggest splitting HTML/CSS/JS into different files Your use of indention and whitespaces is inconsistent function launchFullscreen(element) { if(element.requestFullscreen) { element.requestFullscreen(); has an indention of two spaces snake.game = (...


10

When using HTML local storage, you should always check for the possibility of failure. Some possible failure modes are: Local storage is not supported by the browser Local storage is prohibited for that domain by policy The storage quota has been exceeded Therefore, instead of checking if(typeof(Storage) !== "undefined"), you should wrap the operations in ...


10

Sluggishness Memory limits Take a look at a random folder of images on your computer, and observe it's size. Thousands of images will amount to gigabytes of space, which means all that needs to be loaded into memory. You can simply not do that reliably. There is also not really a point in rendering things that the user cannot see. Thousands or millions ...


9

From a once over: Good I like how you use an IIFE I really like how you use direction = keys[event.keyCode]; Not so good You are not consistently applying the 2nd good technique, for example this: function setWay(direction) { switch(direction) { case 'left': if(old_direction!='right') { ...


8

From what I understand, you don't need to draw the image every time the event mouseover/mouseout is triggered. The only thing that changes when the mouse moves is the radius of the colored circle. I mean the following code could be done only once on the initialization process: _self.ctx.fillStyle = '#fff'; _self.ctx.fillRect(0, 0, _self.width, _self.height);...


8

This turned out to be a bit lengthy. I am not sure if I covered everything, but this should help you with cleaning up your code. JSLint Strings In Javascript strings can be surrounded by both double quotes and single quotes. JSLint wants you to turn all single quoted strings into double quoted strings to make strings uniform. If you need to use a double ...


8

Why do you need to display thousands/millions images? Without knowing that, it's hard to propose a good solution. Perhaps you could just generate that large background once on server side and serve it as a static image? Perhaps you don't need to display them all at once, and could render more of them as the user scrolls down the page?


8

Code review I like the name "Snake on a plane" and was hoping to see some wings and the like. Maybe that's to come. Not bad if this is your first game. I have gone over it from top to bottom and jotted down points as I found them. Some points Don't timeout requestAnimationFrame because you will get inconsistent frame rates. Use a frame counter and skip ...


7

Cool program! I have put my review of the code on JsFiddle. A basic synopsis of what I thought to improve: Everything constant about the map, ship, lasers, and keycodes is all in one place to improve scalability. I used object literals and array literals instead of new Object() and new Array() because using them is shorter and and makes things easier to ...


7

I understand that this might not be actually what you want but I've recreated your effect using only CSS instead of canvas. Although it employs some CSS magic, I think it's much simpler than using canvas for this, and you wont need to worry about performance. div { width: 300px; height: 300px; position: relative; overflow: hidden; ...


7

First off, I'd like to say that your code is very neat and well-written for the most part. Objects/Classes I find that, in your classes, you return a unnamed object with all the desired fields and methods. It would make more sense if, instead of returning an object, to set all the fields and methods in the class itself, and then return this. Advantages to ...


6

From a once-over, Short 1 letter variables are terrible ( except for x and y ), b, p and W are just terrible Also please spellcheck your variables: padles -> paddles You should only detect collision when the ball is going to the left and gets in the danger-zone or when it is going to the right and getting in the danger-zone. So instead of doing 8 accesses, ...


6

That is an awesome animation! From a technical viewpoint, I find it neat how you render the flakes into a PNG represented by a data URI. Realism A lot of the snowflakes look quite nice. But I see some square, pentagonal and heptagonal snowflakes! What kind of chemicals are you using? Is that even mathematically possible? Is some atmospheric condition ...


6

Performance The main reason for the slow down are the state changes you incur each time you change the color and transparency of the particle (which is each particle). Unless you are prepared to write some shaders (webGL) you are not going to get past this problem. You will need to sacrifice some features to get performance. The second reason for the ...


5

After back and forth with ChrisW and yourself, it seems I found a glaring bug var frameFix = function() { hContext.drawImage(sourceVid, 0, 0, sourceVid.videoWidth, sourceVid.videoHeight); var frame = hContext.getImageData(0, 0, sourceVid.videoWidth, sourceVid.videoHeight); var length = frame.data.length; for (var i = 0;...


5

If I redraw it, It become a bit laggy. In my tests, using createImageData and putImageData to fill the individual pixels ran about 3x faster than rect and fill. You can replace this code: GAContext.beginPath(); GAContext.fillStyle = "rgb(" + rG + ", " + gG + ", " + bG + ")"; GAContext.rect(xColor, yColor, 1, 1); GAContext.fill(); With this: pixelData[0] ...


5

The way you check the bounds of r, g, b is a bit repetitive: if(r > 255) r = 255; else if(r < 0) r = 0; else if(g > 255) g = 255; else if(g < 0) g = 0; else if(b > 255) b = 255; else if(b < 0) b = 0; You could use a helper function to simplify a bit: function ensureBounds(x) { return Math.min(255, Math.max(0, x)); // Thanks @...


5

This code is pretty well written, although there are a few things that really bug me a little. First off, inline comments, like the one you've positioned inside that for loop, are eyesores to look at. Preferably, comments should stay on their own separate lines. Secondly, your naming could be improved. For example, what does the variable cen do? It's name ...


5

You can't currently play with the numbers on the numpad of a keyboard - they have different keycodes to the numbers along the top. It's normal to camelCase function names rather than snake_case. Avoid abbreviations e.g. the gen in gen_single_digit_expression. function number_from_keycode(keycode) { - keycode isn't a keycode at all, it's an event. Try to ...


5

Dead Code else{ //undefined data object } This isn't doing anything, so just delete it. Enums Right here, you are using a string literal to specify the player who needs to move: this.player = "x"; Typically, you would use a player enum to specify the player. Spacing If you put spaces around your operators, your code is easier to read, ...


5

You are running three statements repeatly for no reason. Try this: var drawGrid = function(w, h, id) { var canvas = document.getElementById(id); var ctx = canvas.getContext('2d'); ctx.canvas.width = w; ctx.canvas.height = h; for (x = 0; x <= w; x += 20) { ctx.moveTo(x, 0); ctx.lineTo(x, h); for (y = 0; y <=...


5

Use diagonals. The idea is to have only one pixel check, compared to two you have now: find the first occupied pixel on a diagonal skip to an unoccupied one fill with 0.1 while unoccupied repeat 1-3 until out of bounds Considering everything should be inlined, the code would be like this: var x, y, index, index0, len = width * height * 4, stride =...


5

Don't use a wildcard import Wildcard imports are discouraged by PEP8. Instead, I recommend doing imports like this: import tkinter as tk You will then have to change all of the code that references classes, functions, and constance to include the prefix tk. (eg: window = tk.Tk()) Put all imports at the top of the file You have this stuck in the middle ...


5

General problems It is better to add events via addEventListener rather than in the HTML, this keeps the source code together making it easier to maintain. It also protects your code from 3rd party code overwriting the event handler. If some code later sets window.onload = theirFunction; it overwrites your event that will not get called. Keep your variables ...


5

Potential Bug: the score doesn't appear to reset - should it go back to 0 when the button labeled Start is clicked?? const can be used for any variable that is never re-assigned. Some argue const should be the default keyword and then if and only if re-assignment is necessary then use let posMatch can be simplified - from: let posMatch=(pos1,pos2)=>{ ...


4

Most of your code is API calls. I'm surprised that Javascript is fast enough to run at all (it isn't, on my old laptop, using Chrome browser). I'll assume that using completely different APIs, and for example writing a plug-in in a different, compiled language (if that's even possible) is out-of-scope for this question. Therefore I guess that the only ...


4

Interesting, http://jsperf.com/path-rect-vs-fillrect/7 will tell you that fillRect is faster than what you use in clearCanvas. window.onload <- consider using addEventListener instead of assigning straight to window.onload (deltaTime / 1000) <- you should cache this, division is expensive game.previousTime += deltaTime; <- Cant you just game....


Only top voted, non community-wiki answers of a minimum length are eligible