創(chuàng)建 canvas 的方法很簡單,只需要在 HTML 頁面中添加 <canvas> 元素:
<canvas id="myCanvas" width="300" height="150">
Fallback content, in case the browser does not support Canvas.
</canvas>為了能在 JavaScript 中引用元素,最好給元素設置 ID ;也需要給 canvas 設定高度和寬度。
// Get a reference to the element.
var elem = document.getElementById('myCanvas');
// Always check for properties 和 methods, to make sure your code doesn't break
// in other browsers.
if (elem && elem.getContext) {
// Get the 2d context.
// Remember: you can only initialize one context per element.
var context = elem.getContext('2d');
if (context) {
// You are done! Now you can draw your first rectangle.
// You only need to provide the (x,y) coordinates, followed by the width and
// height dimensions.
context.fillRect(0, 0, 150, 100);
}
}
可以把上面代碼放置在文檔 head 部分中,或者放在外部文件中。 2D context API 介紹了如何創(chuàng)建 canvas 后,讓我們來看看 2D canvas API,看看能用這些函數(shù)做些什么。