前へ 次へ
Firefox 3 から canvas 要素で文字を描けるようになりました。で、その例を色々みてみると、描画内容を初期化するために canvas 要素の width と height プロパティを弄っている例が多いです。しかし ctx.clearRect() で十分です。
canvas
width
height
ctx.clearRect()
ただし ctx.clearRect() は ctx.translate() 等の変形の影響を受けるので、 ctx.save() と ctx.restore() をお忘れなく (あるいは ctx.setTransform(1, 0, 0, 1, 0, 0))。
ctx.translate()
ctx.save()
ctx.restore()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ということで、higeorange さんの例を勝手に弄ってみます。higeorange さんのコードを以下に示します。
var canvas = $('cnvs'); canvas.width = 300; canvas.height = 100; var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 300, 100); ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozTextStyle = "30pt sans-serf"; ctx.mozDrawText(txt);
ctx.clearRect() を使っておられるわけですが、たとえば以下のように書けます。
var canvas = $('cnvs'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 300, 100); ctx.save(); // コンテクストの状態を保存 ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozTextStyle = "30pt sans-serf"; ctx.mozDrawText(txt); ctx.restore(); // コンテクストの状態を save() した時の状態に復帰
あるいは以下のようにも書けます。
var canvas = $('cnvs'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 300, 100); ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozTextStyle = "30pt sans-serf"; ctx.mozDrawText(txt); ctx.setTransform(1, 0, 0, 1, 0, 0); // 変形行列を単位行列に
Firefox 3 でのテキスト API は独自のものですが、mozilla-central では既に HTML 5 草案の API に対応しています。
canvas 要素の width と height を設定すると、Gecko は描画対象 (gfxASurface) と描画コンテクスト (gfxContext) を一度破棄してから再度作成・初期化します。
gfxASurface
gfxContext
一方、 ctx.clearRect() は描かれている領域の一部をクリアするだけで、 surface を破棄したり再作成したりということはありません。
詳細検索
random Hatena Ring svg
random Hatena Ring firefox
random Hatena Ring pblog
Firefox 3 から
canvas要素で文字を描けるようになりました。で、その例を色々みてみると、描画内容を初期化するためにcanvas要素のwidthとheightプロパティを弄っている例が多いです。しかしctx.clearRect()で十分です。ただし
ctx.clearRect()はctx.translate()等の変形の影響を受けるので、ctx.save()とctx.restore()をお忘れなく (あるいはctx.setTransform(1, 0, 0, 1, 0, 0))。ということで、higeorange さんの例を勝手に弄ってみます。higeorange さんのコードを以下に示します。
ctx.clearRect()を使っておられるわけですが、たとえば以下のように書けます。var canvas = $('cnvs'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 300, 100); ctx.save(); // コンテクストの状態を保存 ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozTextStyle = "30pt sans-serf"; ctx.mozDrawText(txt); ctx.restore(); // コンテクストの状態を save() した時の状態に復帰あるいは以下のようにも書けます。
var canvas = $('cnvs'); var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, 300, 100); ctx.translate(10, 50); ctx.fillStyle = "Red"; ctx.mozTextStyle = "30pt sans-serf"; ctx.mozDrawText(txt); ctx.setTransform(1, 0, 0, 1, 0, 0); // 変形行列を単位行列に蛇足 1
Firefox 3 でのテキスト API は独自のものですが、mozilla-central では既に HTML 5 草案の API に対応しています。
蛇足 2
canvas要素のwidthとheightを設定すると、Gecko は描画対象 (gfxASurface) と描画コンテクスト (gfxContext) を一度破棄してから再度作成・初期化します。一方、
ctx.clearRect()は描かれている領域の一部をクリアするだけで、 surface を破棄したり再作成したりということはありません。