What is Canvas
Although there are many tutorials about Canvas in Mozilla, I decided to record my learning process. If you feel that what I wrote is not clear enough, you can find a link to the Canvas tutorial on the Mozilla website in the references.
Also, some interesting Canvas examples can be found here.
Get started with Canvas
Using Canvas is very simple. Just like using other HTML elements, you only need to add a
Firefox 3.0.x 的尴尬
Firefox 3.0.x 虽然支持了 canvas 元素,但是并没有完全按照规范来实现,规范中的 fillText、measureText 两个方法在 Firefox 3.0.x 中被几个 Firefox 特有的方法代替,因此在 Firefox 3.0.x 中使用 Canvas 时需要先 fix 这个几个方法在不同浏览器中的差别。
下面这代码取自 Mozilla Bespin 项目,它修正了 Firefox 3.0.x 中 Canvas 的 Context 对象与 HTML5 规范不一致的地方:
注意:到 Opera 9.5 为止,Opera 还不支持 HTML5 规范中 Canvas 对象的 fillText 以及其相关方法和属性。
Hello, Canvas!
在对 Canvas 进行了一些初步了解后,开始来写我们的第一个 Canvas 程序,闻名的 HelloWorld 的又一个分支“Hello, Canvas”:
Run the example and the area where the Canvas object is located displays "Hello, World!". This is exactly what ctx.fillText("Hello, World!", 20, 20); in the code does.
fillText and related attributes
ThefillText method is used to display text in Canvas. It can accept four parameters, the last one of which is optional:
void fillText(in DOMString text, in float x, in float y, [Optional] in float maxWidth);
where maxWidth represents the maximum width when displaying text, which can prevent text from overflowing. However, in my tests, I found that specifying maxWidth in Firefox and Chomre has no effect.
Before using the fillText method, you can adjust the font of the displayed text by setting the font attribute of the Context. In the above example, I used "20pt Arial" as the font of the displayed text. You can set different values yourself. Look at the specific effects.
End
That’s it for now, I will write this series while reading the specifications:)
Reference materials
1. HTML5 Canvas, a new stage for scripting languages, hred
3. Canvas Tutorial Chinese, Mozilla