📜 ⬆️ ⬇️

Canvas FAQ


A few days ago I suggested asking questions on Canvas on Habré. Under Habrakat - answers to 27 questions.


1. Why do I need Canvas, what is it all about, what is browser support, what is the main area of ​​application, how developed are the frameworks, examples?


Canvas is a low-level API for drawing graphics. Supported by all modern browsers. Naturally not supported by older versions of IE (8 and below)
The frameworks are evolving, although they still need to grow up. Basic examples can be found at MDC . More powerful examples can be searched on sites a la Chrome Experiments or in examples of applications on frameworks, for example LibCanvas

2. When should I use Canvas, and when should I use Flash?



Flash is faster, cross-browser, with good tools and frameworks.
Canvas is currently used mainly by enthusiasts and experimenters.
There is no special reason to leave the flasher from the market.
But such large players as Google, Mozilla, Apple, Microsoft are engaged in Canvas, they all optimize and speed up the rendering of Canvas, gradually disappear old browsers and new ones come. Look at Firefox 2.0 and Firefox 4.0. For three years, the speed increased by an order of magnitude and the main leap was made with the release of the fourth version. Similarly - Opera. Also, during this time Chrome managed to appear and release 12 major versions of its browser. In general, HTML5 and Canvas in particular have a bright future.
')

3. When to use Canvas, and when SVG?


This is a holivar topic. There are different views on it.
Read this discussion: habrahabr.ru/blogs/javascript/114129/#comment_3678242
See this picture:

Read the article " Thoughts on when to use Canvas and SVG "

On the one hand, when using Canvas, you will need to implement what is already implemented in SVG. On the other hand, in the Canvas, you can apply such optimizations that are impossible in the SVG, for example, drawing from the cache.

On mobile phones, the actual use of CSS3 instead of SVG and Canvas, because It is accelerated by hardware and works very smoothly.

4. What literature to read?


I recommend starting with the Mozilla Developers Network , it’s very cool and the basics of Canvas are described here with examples. After that, invent yourself a task and try to implement it. The API is very simple, the main thing is experience.

There is a fresh book " HTML5 Canvas " by O'Reilly Media. I have not read, but O'Reilly usually produces cool books.


5. How to make screenshot Canvas?


There is a small library canvas2image that allows you to save Canvas to the server, to the client. On the client, saving is done using toDataURL. The server gets the content using getImageData, is translated to base64 code and sent by a POST request. On the server, it is enough to do something like this code:

if (empty($_POST['data'])) exit; $data = $_POST['data']; $name = md5($data); $file = "$path/$name.png"; if (!file_exists($file)) { $image = str_replace(" ", "+", $data); $image = substr($image, strpos($image, ",")); file_put_contents($file, base64_decode($image)); } echo $file; 


Also, the answer from azproduction
If “Canvas screenshot === Save the canvas as a picture”, then:

 /*  */ canvas.getAsFile("test.jpg", "image/jpeg"); // File https://developer.mozilla.org/en/DOM/File /*  */ canvas.toDataURL(); // String  data url /*  */ function test() { var canvas = document.getElementById("canvas"); var f = canvas.mozGetAsFile("test.png"); var newImg = document.createElement("img"); newImg.src = f.toDataURL(); document.body.appendChild(newImg); } 

Read

Important You must set the fixed dimensions of the canvas (via width / height or style), otherwise you will get bad data from toDataURL


6. Interested in methods of improving performance (raising fps).


There are various optimization methods that depend on the application. I described three of them in the topic of Fifteen on LibCanvas . It:
* Update canvas only when needed
* Instead of redrawing the entire canvas, redraw only the changed pieces.
* Drawing objects into the buffer (which allows you to draw an object each frame as a set of pixels, rather than applying all filters and a bunch of matan)
You will be greatly helped by the profiler in your favorite browser.

7. Work with video capture


azproduction :
If you're talking about capturing video from the camera:
The API is only in the draft draft of the Media Capture API. The closest release of the specification is possible in PhoneGap - perhaps there is a trunk. Working with him will be very easy. The handler hangs on the “device”, each frame is transmitted as an image in the data uri format:
 function success(data) { var container = document.createElement("div"); for (var i in data) { var img = document.createElement("img"); img.src = data[i].url; container.appendChild(img); } document.body.appendChild(container); } function error(err) { if (err.code === err.CAPTURE_INTERNAL_ERR) { alert("The capture failed due to an internal error."); } else { alert("Other error occured."); } } navigator.device.capture.captureImage(success, error, { limit: 1 }); 



8. What is the most effective solution at the moment for pixel-by-pixel access when drawing an arbitrary image to a Canvas (without WebGL)? For example, hand-drawn faces when building 3D using Gouraud / Phongue shading.


Look at two topics:
habrahabr.ru/blogs/crazydev/93594
habrahabr.ru/blogs/crazydev/94519

For pixel-by-pixel access, there is only one solution - use getImageData

9. Are there ways to scale the canvas with all the insides to fit the screen effectively and cross-platform?


Try using css. canvas {width: 100%; height: 100%; }. Something like this. But the js-code should take into account this piece, because the coordinates will shift.

10. Support and speed on Android / iOS devices


Supported fully. True, I on iPhone2 noticed the lack of support for fillText, but this is the only thing.
Performance problem, but something can be run. While for mobile phones it is better to use CSS3. Perhaps in the future, something will change.

11. Interested in the fastest way to draw a point (for example, for graphics). Single-pixel and four-pixel, arbitrary color.


The fastest in terms of performance is to use fillRect for single renderings and getImageData + putImageData for mass renders.

12. In what form the “world” is stored, displayed and redrawn in games with a side view (like playbiolab.com), i.e. the player ran to the right the camera moved with him and the world "moved"


I do not know exactly how it is done in biolab. There are several ways. You can overlay several canvas layers on each other, draw on the lower world and display the desired part using CSS.

13. 3d-canvas


Three.js - 3d Javascript engine

14. Editors - what to write?


Any JavaScript editor is suitable. I used to use Netbeans 7, now I switched to Jetbrains WebIde

15. Database


For storing data on the client side, there are two modern standards - webStorage and IndexedDB .
IndexedDB is a cool interface with a bunch of features, described on Habré , and webStorage is a simple key-value store

16. Canvas and IE


In IE, version 9 is not supported. All attempts to make it supported can be called suitable only for a very narrow range of tasks and do not give imputed speed.
IMHO, the only option is Google Chrome Frame , a plugin that installs on a semi-browser as Flash or SilverLight and turns shit into a candy Internet Explorer into a modern browser.

17. How to calculate the distance between the drawn objects, whether there are ready-made solutions


Depends on objects. Some things are done very simply. For example, the distance between points is considered according to the Pythagorean theorem. Between the circles - count the distance between points from submultiples. More complex figures have their own laws.
Something (at least the intersection of rectangles / circles / polygons) is already in LibCanvas . If you have any special requirements - you need to look for algorithms. I can advise this:
Known collision detection and response algorithms in flash.

18. How and by what means is it better to do animations on Canvas?


Recently there was a good topic " Animation and Canvas ". Also, in the comments I talked about my implementation with the help of LibCanvas .

19. Work with text in Canvas (including animation)


The text is drawn with fillText / strokeText . Your fonts can be connected using CSS3 .
It is affected by all the rules - such as shadows, transformations, setting colors, etc. For example, with the help of a light shade on a dark background, you can easily make a glowing text

20. Work with images.


How to work with images is very coolly described in the MDC .

21. Using Backbuffer, how to draw one Canvas into another.


You can draw any information into a hidden Canvas, which is then used just like a picture (see previous item).
Buffering allows you to speed up the drawing repeatedly. For example, drawing one gradient from the buffer is 5 times faster than drawing the same gradient directly .
It is very easy to use:
 //    : var buffer = document.createElement('canvas'); buffer.width = 64; buffer.height = 32; buffer.ctx = buffer.getContext('2d'); //    LibCanvas: var buffer = LibCanvas.Buffer(64, 32, true); //      buffer.ctx.fillRect(/* */) //     : var ctx = canvas.getContext('2d'); ctx.drawImage( buffer, 0, 0 ); 


22. Animation in canvas is done using the full redraw method. Thus, information about all objects is stored in the JS object and is redrawn every time, or how to create sprites and layers?


Yes, there are various techniques. You can use buffers in order not to draw dozens of small objects, you can redraw the canvas only partially, but more often it’s cheaper to just redraw everything than to understand what needs to be redrawn and what isn’t.

23. I would like to know how to draw a 3D object using canvas (preferably with a perspective) and rotate it?


HTML5 Experiment: A Rotating Solid Cube

24. Drawing SVG in Canvas


Can with CanVG . Almost no sense)

25. How different is browser support, or does everyone follow the standard?


The differences are minimal. There were minor bugs, minor inconsistencies. For example, Opera could not draw a rectangle with negative side sizes:
 ctx.fillRect(50, 50, -20, -20); 

Pictures are compressed and rotated in different ways. For example, in Chrome, when turning at the corners, teeth are noticeable (no smoothing)

But he is better than Fx and Opera stretches the images:


There are still minor differences in javascript. For example, in some browsers, sort implements an unstable sort, so if the elements are sorted by Z-index, then elements with the same Z-index will be swapped.

These are very small nuances. Most are hidden behind friendly framework APIs. Personally, I develop only for one browser and in most cases everything works perfectly in the rest.

26. putImageData vs drawImage


I'll be brief - putImageData is much slower . Moreover, with the increase in the size of the picture - the slowness increases.

27. I would be very interested to hear about typical implementations of the main functionality of canvas libraries, such as: emulating layers, defining the active element (where the cursor is currently located), creating an event management system, etc.


This question was asked to me more often, because for him - a separate topic )

Unanswered Questions


Guys, who can give answers to these questions - please in the comments

1. How to display text on canvas in IE (IE8- + excanvas.js)? I tried text.canvas.js from google code - it displays an error about the lack of something glyphs.
I do not use emulation in IE

2. Are there any secret libraries that can draw lines of varying thickness? In the case of straight lines, it is relatively easy to implement in a “crutch” way, but all Bezier curves are apparently only at a low pixel level.

3. Are there any secret libraries that can draw gradient coloring lines. Well, that is, so that the color smoothly changes between nodes along the line, not necessarily straight. Such a function is, for example, in OpenGL.

Conclusion


If something is not clear - ask questions, we will supplement) If your question is not answered or even not asked - ask again in the comments. If you don't have a reg, you can email me at shocksilien@gmail.com
Like this topic format?

Source: https://habr.com/ru/post/119772/


All Articles