Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ทำให้ HTML5 Canvas ขยายเต็มหน้าจอ (Full Page)

CSS ทำให้ Canvas เต็ม Viewport

* { margin: 0; padding: 0; }
html, body { height: 100%; overflow: hidden; }
#canvas {
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    display: block; /* ป้องกัน whitespace ด้านล่าง */
}

JavaScript ปรับขนาดจริง (Device Pixels)

var canvas = document.getElementById('canvas');
function resize() {
    canvas.width = window.innerWidth * devicePixelRatio;
    canvas.height = window.innerHeight * devicePixelRatio;
    canvas.style.width = window.innerWidth + 'px';
    canvas.style.height = window.innerHeight + 'px';
    canvas.getContext('2d').scale(devicePixelRatio, devicePixelRatio);
}
window.addEventListener('resize', resize);
resize();

ตั้ง canvas.width/height ให้ตรงกับ Device Pixels ป้องกันเบลอบน Retina/High-DPI