<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 介绍了如何创建 canvas 后,让我们来看看 2D canvas API,看看能用这些函数做些什么。