Performance of mouseover on canvas vs mouse enter on html object - javascript

I have a circle drawn on a canvas. At the moment i use canvas.mousemove to determine wether the mouse is inside the circle. Would it be better perfomancewise to place a round html object over the canvas and use the mouse enter and leave events of this html element? I think so because mouse move triggers more often.

In case of small amount of objects it does not matter - just take the approach that is more convenient for you.
For thousands of objects to check - pure canvas based approach shall be faster, more readable and occupy less memory.
In my personal taste layering anything above canvas to catch events or display anything is a misunderstanding.

Related

Render objects based on 1 specific object on the canvas

I'm presently implementing a few features into a vector editor based off of fabric.js and have hit a bump in the road with how best to handle this scenario:
In order to resize/scale the canvas smaller and larger via scaling grippies/controls, I've begun the task of implementing a "fake canvas" that stays in the middle of the real canvas (the real canvas is resized to fill it's DOM parent at all times. This presents several issues, the biggest being, dealing with objects on the canvas, ensuring their coordinate are always relative to my "fake canvas" (which is just a Rect with some restrictions applied, e.g. locking movement, rotation, etc).
So I'm really just looking for strategies/suggestions at how to go about doing this. For instance, I know I'd be dealing with newly added objects, moving objects and preventing them to be moved outside of the boundaries of my fake canvas. Among other considerations.
Thanks for the input and suggestions. I'm not looking for code, I'm more just looking for suggestions of how best to handle all the canvas related things, transferred to a fake canvas. I see that the Shutterstock Editor does some of this too, so I guess it doesn't seem like it's out of the realm of possibilities.

Best/easiest way to make a 2D Chess board using Javascript/HTML5?

I am building a web based chess game in Javascript. I'm using the HTML5 canvas to display the board by drawing rectangles.
I am trying to implement the move logic. So when a chess piece is clicked, and then they click on an empty block, I want to move it. However, it is quite tedious using the canvas. I need to do the following:
Update my 2D grid of objects to reflect the change, I set the current
square to undefined and set the new square to the object being moved
clearRect(..) which I still haven't got to work
Redraw the image at the new position
Is there a better way?
Also, how do I deal with the 'double click'. I currently using a boolean that holds if the piece was pressed, and if it was and they click on an empty square I call the move function. Are there any other ways of doing this? Additionally, are there any tools for making it seem like the chess piece is being dragged?
I appreciate any help. Thanks guys.
Over the years I've written a lot of chessboards for HTML. In the end the simplest approach I think is:
Keep an array (either 1d or 2d, both have pros and cons) with just piece names (e.g. "wp"=white pawn, "bn"=black night, "--" empty). Nothing to be gained with an OO-approach or even a generic piece object.
Use one single canvas for the board, drawing the pieces on them with drawImage.
Write a function that just draws everything and call it when needed (don't bother erasing/drawing single pieces).
For piece dragging empty the square and create a separate dragged div containing just the dragged piece (redrawing the full board during drag can be slow for low-end mobile devices).
For dragging attach move and up handlers to the document and not to the canvas, so that you won't miss up events when the mouse is outside of the browser window.
Start dragging on mousedown and attach events for mousemove and mouseup. This will work both on computers and on mobile phones without having to handle specific cases. Always call preventDefault and stopPropagation.
Make full-page view with no overflow and handle resize yourself (you'll need to add some mobile-specific metas to stop phones messing up with the page).
HTML can really do impressive things with just 2d canvas, as an example see this 2d/3d chessboard. One single file less than 300k (200k zipped).
Easiest you say?
Using chessboard.js has to be the easiest way and it is 2D.
HTML
<div id="board1" style="width: 400px"></div>
JavaScript
var board1 = ChessBoard('board1', 'start');
It has very good documentation and tons of different examples (customization) and can be downloaded here.
Learning by coding -- Good for you!
Here are a few tips to get you started:
A reusable structure for your game:
Create a JS object for each of your chess pieces and save those piece-objects in an array.
// an example piece object
var blackKing={
player:'black',
pieceType:'king',
image:blackKingImageObject,
currentSquare:['E','1'],
isCaptured: false,
// etc...
}
// a pieces-array
var pieces=[];
pieces.push(blackKing);
Create a function that does all of these things:
clearRect the entire canvas,
redraw the chess board,
use the piece-array to redraw all the pieces onto the chessboard.
About click vs double-click vs dragging:
Yes, that's troublesome and requires special handling.
Many coders handle it this way:
Listen for mousedown and save that timestamp and initial mouse position.
If a mouseup plus another mousedown occurs quickly it's a double-click.
If a mousemove of more than a few pixels occurs then it's the start of a drag.
Otherwise, it's a single-click.

Pixel-by-pixel animation with javascript

I'm animating a sprite on a pixel grid. I have a few options, with pros and cons for each. I have a fair amount of javascript experience (six years), but none with this kind of thing. The problem is I don't know how expensive each option will be.
The sprite needs to render quite fast, and be inexpensive enough to have at least five running at the same time while running collision detection.
Ideally, I would like to use a grid of elements inside of a wrapper, rendering colour and alpha channels to each element from a multidimensional array.
The major pro here is that I can run pixel-by-pixel collision detection and click past the transparent parts of the sprite. With any image-based sprite, the onClick event will fire even if I click on a transparent pixel (I'll have to do a lot of work to pass clicks through transparent pixels, and it might be quite expensive).
The next option is to use css sprites. css-tricks.com/css-sprites/
This would be easy peasy, but as mentioned previously, onClicks won't pass through the transparent pixels. I can probably force it, but again, it may be expensive, and take a lot of time to impliment.
Another option is animated gifs, but they are huge, limited in the colour department, and hard to control animation-wise. I'd rather not go there.
And then there's the html5 canvas element, which I don't know very much about and would like to stay away from if at all possible. I don't know how any of my code would even work in relation to the canvas element and I doubt it would do what I want in the long-run.
So which is the best for performance? Would the first (and most preferable) be a viable option? Or have I missed something out?
With today's browsers you will be fine on desktop computers for building a sprite out of positioned pixel sub-elements (as long as they aren't too complicated or large), and just to be safe I'd limit yourself to about 10 active sprites. With Mobile things might get a bit slow and clunky, but considering you seem to be designing a game that requires precision "onclicks" I doubt that this will be a problem.
Your most flexible bet is to use HTML5 Canvas, as you have already worked out, but it will involve quite a bit more JavaScript coding. But this sytem will allow you to apply a number of effects to your sprites and will allow you to use pixel perfect detection by using getImageData (which allows you to read the exact pixel colour at any pixel offset).
getPixel from HTML Canvas?
If you wanted to avoid the techinical problems and challenges of having a full screen canvas system (which can be tricky), you can actually create as many smaller Canvas elements and move them around as your sprites (with the ease of HTML Elements).. Then all you have to do is design the code that draws your animation frames, and also tells if the mouse has hit or not hit the sprite using the aforementioned method (along with a click handler and some code to calculate where the user has clicked relative to your canvas elements position). Obviously, it would be best to do this in a generalised way so your code can be applied to all your sprites :)
To draw your images on the canvas you can use a spritesheet as you were mentioning in your question, and use the rather flexible drawImage() method which supports a slicing mode. This just needs to be tied up to a setInterval or requestAnimationFrame style game loop.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images
http://www.playmycode.com/blog/2011/08/building-a-game-mainloop-in-javascript/
UPDATE - for those who wish to be very optimal
If you wish to take a more optimal route - which is a little bit more involved again - you can do the following. This method benefits if you have many sprites that are exactly the same with only a few (20 or 30) frames of animation:
Power your sprites by normal DIVs with a background image sprite sheet that you shift the background position of. This is the most optimal you can be, save having static images as sprites, because the browser does all the work.
for each sprite type draw your spritesheet on a hidden canvas element that is big enough to incorporate your whole spritesheet.
When a user clicks on one of your DIV sprites, take the background position as coordinates, invert them, and you should then know where on your canvas element (looked up by sprite's type) the pixel data resides.
Use the getPixelData method on your hidden canvas to work out if the user has clicked on the sprite or not.
The above means you only have one canvas element in use - per sprite type, the browser handles all the graphics for you and you get pixel perfect collisions with an onclick.
Hope the above makes sense?
How about splitting your image spirit into 30x30 cells and only have elements where the cell is opaque and leave a gap where the cell is transparent so that clicks fall through. You lose a bit of accuracy in where the cells can be clicked though.

HTML canvas events on overlapping objects?

If I have a canvas with a circle that changes color upon clicking on it, I can use a click event on the canvas element and handle the math for that (distance formula calculation <= radius). But what if I have two circles that overlap (like a van diagram), and I click in the middle of the two circles assuming that only the top circle should change color? If the math of the first circle is applied in this case, both circles would change color.
How would I deal with events in the canvas in terms of overlapping objects like the example above? With hopefully a fast/efficient algorithm?
You might want a framework like EaselJS that has a better api for what you're trying to do. Barebones canvas 2d-context doesn't provide much in terms of display-object / sprite behavior.
Responses above also mention some sort of list to represent layers. I don't think the implementation would be very difficult, just another condition to check for along with the radius.
Canvas isn't really like Flash or like a DOM tree whereby things have sort orders or z-indexes. Its a bit more like a flat rastered image and you have to rely upon other logic in your javascript to remember the sequence & stacking order of things you have drawn.
If you need this kind of interactivity I've always found it best to use a 3rd party library (unless it really is just a case of one or two circles which dont do much).
For interactive 'shape' based javascript graphics I would sugest Raphael.js or D3 which are actually more of SVG tools than a canvas one so maybe it's not for you but they are simple and cross-browser.
There's also processing.js (js port of Processing the Java lib) which feels a bit like flash and again can track all of the levels and objects. Theres a tonne of others but thats another topic.
If it's super simple the options might be:
Hold the co-ordinates of all shapes/elements composited on the canvas inside an object or array which also tracks their z-index/sort sequence, thereby letting you know whats on top.
Using the imagedata at the mouse coordinate of the click to establish what has been clicked
using multiple canvases composited on each other and letting the DOM do the work for the click events

Between SVG and canvas, which is better suited for manipulating/animating several images? Maybe neither and just use css3 transforms?

The 2nd part of the question is, which javascript library is better/easier to manipulate images with? I won't be actually drawing any shapes or anything. Other info: I'll be using jQuery and don't need to support all browsers, just webkit.
Edit:
More information: the current design is to layout/draw several rows/columns of images in a grid-like layout, with the image in the center being in "focus" (a little larger, with a border or something and some text next to it). The tricky thing is that we want the whole canvas of images to appear to slide/glide over to bring another random image into focus. So obviously the number of images in this grid needs to exceed what is visible in the viewport so that when the transition occurs there are always images occupying the canvas. Other than moving the images around, I won't be blurring them or otherwise modifying them. Eventually we will add user interactions like clicking/touching on a visible image to bring it to focus manually.
Let me know if this is not clear or still confusing.
I ran across scripty2 which seems like an alternative to using canvas/SVG for my purposes. I also started farting around with EaselJS last night, and it seems like this might work, but I'm wondering if it'll end up being more work/complex than just using standard HTML/CSS and a tool like Scripty2 to aid with animations and click/touch events. Just looking for any suggestions. Thanks!
The answer depends on your manipulation and animation.
If it's just translations, CSS wins for speed compared to canvas. I haven't tested, but I feel confident it easily beats SVG for the same sort of thing.
If you're going to be doing non-affine transformations or otherwise messing with the images (e.g. blurring them) you clearly want Canvas.
If you need event handlers per object, you clearly want a retained-mode drawing system like SVG or HTML+CSS. I haven't done enough CSS3 transforms to say how they compare in terms of speed to SVG, but they clearly do not have the robust transformation DOM of SVG.
This is a rather subjective question (or suite of questions) and you haven't yet given sufficient information for a clear answer to be possible.

Categories