Canvas API

<canvas>HTML5 的新元素,可透過 Script(通常是 JavaScript)繪製圖形。例如,可以用來繪圖、合成圖照片、建立動畫、甚至處理即時的影片播放。

Mozilla 應用程式從 Gecko 1.8(也就是 Firefox 1.5)起開始支援 <canvas>。這個元素最初由蘋果 OS X Dashboard 和 Safari 引入。Internet Explorer 9 以上版本也有支援 <canvas>,但較舊的 IE 版本則須嵌入 Google Explorer Canvas 專案中的程式腳本,才能得到有效的支援。Opera 9 也支援 <canvas>

<canvas> 元素通常也被 WebGL (en-US) 用來在網頁上顯示使用硬體加速繪製的 3D 圖形。

範例

這則簡單的範例使用了CanvasRenderingContext2D.fillRect() (en-US)這個方法。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.fillStyle = "green";
ctx.fillRect(10, 10, 100, 100);

Edit the code below and see your changes update live in the canvas:

參考

教程指南

Canvas tutorial

這個全部的課程包含 <canvas> 基礎的使用和高階的應用。

Code snippets: Canvas

一些延伸的開發功能,包含<canvas>

Demo: A basic ray-caster

使用<canvas>做的光線追蹤(ray-tracing )範例。

Drawing DOM objects into a canvas

如何在 DOM<canvas>之中,畫個物件。例如 HTML 的元素。

Manipulating video using canvas (en-US)

結合<video> (en-US)<canvas> 去控制影像資料的真實時間

資源

Generic

Libraries

  • Fabric.js is an open-source canvas library with SVG parsing capabilities.
  • Kinetic.js is an open-source canvas library focused on interactivity for desktop and mobile applications.
  • Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas.
  • Origami.js is an open source lightweight canvas library.
  • libCanvas 是一個強大且輕量化的 canvas 框架。
  • Processing.js 是視覺化程式語言 Processing 的移植版。
  • PlayCanvas is an open source game engine.
  • Pixi.js is an open source game engine.
  • PlotKit 是一個製作圖表和圖形的函式庫。
  • Rekapi 是一個用來控制動畫影格的 Canvas API。
  • PhiloGL 是一個可應用在資料視覺化、遊戲開發的 WebGL 框架。
  • JavaScript InfoVis Toolkit 可在網頁上建立 2D 的互動式 Canvas 視覺化資料。
  • EaselJS 是一個自由 / 開放源始碼的函式庫,目的在簡化 canvas 於遊戲與美術的開發難度,類似 Flash API。
  • Scrawl-canvas is another open-source javascript library for creating and manipulating 2d canvas elements

規範

Specification
HTML Standard
# the-canvas-element

參見