我正在嘗試使用 2d 畫布構建一個超級簡單的像素網格(20x20)。我想使用不同大小的屬性和 CSS 將其放大 (*10)。
我認為它應該以這種方式作業,因為寬度和高度屬性應該表示記錄的網格像素。但是當我使用 CSS 縮放它時,像素以某種方式開始抗鋸齒(?),而不是保持簡單的像素(矩形)。將 antialias 設定為 false,沒有任何效果。
為什么會這樣,有沒有辦法解決它,而無需將比例應用于除 CSS 之外的所有其他內容?(我可以將一個像素設為 10 像素寬,但這破壞了簡單性)。
const element = document.createElement('canvas');
const canvas = element.getContext("2d", {antialias: false});
const size = 20;
const scale = 10;
element.width = size;
element.height = size;
element.style.width = size * scale 'px';
element.style.height = size * scale 'px';
[{x:10, y: 4},
{x:10, y: 6},
{x:10, y: 12},
{x:10, y: 13}]
.forEach(({x, y}) => canvas.fillRect(x, y, 1, 1));
document.body.appendChild(element);
uj5u.com熱心網友回復:
您可以使用影像渲染的 CSS / 樣式,并將其設定為像素化。
例如。
const element = document.createElement('canvas');
const canvas = element.getContext("2d");
element.style.imageRendering = 'pixelated';
const size = 20;
const scale = 10;
element.width = size;
element.height = size;
element.style.width = size * scale 'px';
element.style.height = size * scale 'px';
[{x:10, y: 4},
{x:10, y: 6},
{x:10, y: 12},
{x:10, y: 13}]
.forEach(({x, y}) => canvas.fillRect(x, y, 1, 1));
document.body.appendChild(element);
uj5u.com熱心網友回復:
畫布的寬度和高度屬性在某種意義上是它的真實尺寸。畫布像素根據這些尺寸定位。style.width 和 style.height 是用于在螢屏上顯示畫布元素的尺寸。
所以最終的結果是一個被瀏覽器拉伸的畫布,以滿足這些樣式屬性。這會將 20x20 像素畫布拉伸到 200*200 畫布元素區域。
反而
<head>
<title>stretched canvas</title>
</head>
<body>
</body>
<script>
const element = document.createElement('canvas');
const canvas = element.getContext("2d", {antialias: false});
const size = 20;
const scale = 10;
element.width = size * scale;// scale the true dimensions of the canvas.(i.e the canvas's coordinate system)
element.height = size * scale;
element.style.width = size * scale 'px';
element.style.height = size * scale 'px';
canvas.scale(scale,scale);//now when determining the coordinates, all the dimensions will be pre scaled and so each pixel that will be drawn will be calculated before being rendered instead of being stretched by the browser after
[{x:10, y: 4},
{x:10, y: 6},
{x:10, y: 12},
{x:10, y: 13}]
.forEach(({x, y}) => canvas.fillRect(x, y, 1, 1));
document.body.appendChild(element);
</script>
</html>```
Conclusion:
The canvas api calculates the positions of each pixel based on the width and height attributes.
The browser then scales it up according to the style.width and style.height css properties.
By scaling it in javascript. The positions of the pixels will be calculated before being drawing onscreen.
Set the width and height attributes of the canvas to the wanted dimensions so that the browser won't scale it up after being drawn.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/370033.html
標籤:javascript css 帆布 缩放
