DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5詳解
Canvas fillRect 座標跑掉的元凶:width 與 height 必須寫在標籤上
編輯:HTML5詳解     

先釐清參數本身的意義:fillRect(100, 100, 100, 100) 中,前兩個 100 是座標(x、y),後兩個 100 是寬與高。這部分很多人都知道,但接著就會遇到一個很惱人的現象——明明寫了同樣的數字,畫出來的矩形位置卻跟預期不符。

我當初學 Canvas 時就卡在這裡研究了半天,最後才發現問題不在 fillRect,而在 <canvas> 元素本身的尺寸宣告方式。

錯誤寫法一:用 CSS 指定尺寸

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#mycanvas{
  width: 200px;
  height: 200px;
  background: yellow;
}
</style>
</head>
<body>
<canvas id='mycanvas'></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle = '#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</html>

錯誤寫法二:用行內 style 指定尺寸

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id='mycanvas' style='width:200px;height:200px;background:yellow'></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle = '#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</html>

這兩種寫法都會出問題:矩形可能被裁掉一半,或者位置與比例整個跑掉。

正確寫法:用 canvas 的 width / height 屬性

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id='mycanvas' width='200' height='200' style='background:yellow'></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle = '#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</html>

為什麼會這樣

關鍵在於 canvas 有兩組尺寸,而且它們是完全獨立的:

一是「位圖尺寸」(drawing surface),由 width/height 屬性決定。這決定了畫布實際的像素解析度,也就是你所有繪圖座標所依據的座標系大小。沒有指定時,預設是 300 × 150。

二是「顯示尺寸」,由 CSS 的 width/height 決定。這只影響元素在頁面上被拉成多大,不涉及任何繪圖計算。

當你只用 CSS 設成 200 × 200 卻沒設屬性時,瀏覽器實際拿到的是一張 300 × 150 的位圖,然後把它拉伸/壓縮塞進 200 × 200 的框裡。於是你寫的 fillRect(100, 100, 100, 100) 明明是在 300 × 150 的座標系中,卻被縮放顯示,位置與長寬比自然全亂了。

另外要注意一個小細節:width="200px" 這種帶單位的寫法在部分瀏覽器中並不被接受,HTML 的 width/height 屬性應該只寫數字(width="200"),CSS 才需要加單位。

實務上的建議

如果你確實需要「後面的 CSS 控制顯示大小、但繪圖保持清晰」,正確做法是用屬性設定高解析度的位圖,再用 CSS 縮放顯示,或者直接用 JS 依裝置像素比放大:

var dpr = window.devicePixelRatio || 1;
canvas.width  = 200 * dpr;
canvas.height = 200 * dpr;
canvas.style.width  = "200px";
canvas.style.height = "200px";
ctx.scale(dpr, dpr);   // 讓繪圖座標仍以 200x200 來思考

這樣在高 DPI 螢幕(Retina、多數手機)上才不會出現模糊。順帶一提,用 JS 修改 canvas 的 width 或 height 屬性會清空整個畫布並重設所有 context 狀態,所以要在 resize 之後重新設定 fillStyle、lineWidth 等參數,並重畫內容。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved