Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khắc phục méo hình (distorted) HTML5 Canvas

Canvas HTML5 có kích thước mặc định width=300, height=150 (tỷ lệ 2:1). Nếu bạn đặt CSS width/height khác tỷ lệ này mà không đặt attribute width/height trên thẻ <canvas>, nội dung vẽ sẽ bị méo (stretched).

Nguyên nhân

  • Attribute width/height quyết định kích thước bitmap vẽ (drawing buffer).
  • CSS width/height quyết định kích thước hiển thị (display size).
  • Nếu hai tỷ lệ khác nhau → nội dung bị scale không đồng đều → méo.

Giải pháp: Đặt attribute width/height khớp tỷ lệ hiển thị

<canvas id="canvas1" width="400" height="300"></canvas>

Ví dụ minh họa

<!DOCTYPE HTML>
<html>
  <head>
    <style> #mycanvas { border: 1px solid red; } </style>
  </head>
  <body>
    <canvas id="mycanvas" width="100" height="100"></canvas>
  </body>
</html>

Khắc phục méo hình (distorted) HTML5 Canvas

Best practice

Luôn đặt width và height attribute trên <canvas>. Nếu cần responsive, dùng JavaScript cập nhật attribute khi resize cửa sổ:

function resizeCanvas() {
  const canvas = document.getElementById('mycanvas');
  canvas.width = canvas.clientWidth;
  canvas.height = canvas.clientHeight;
  redraw();
}
window.addEventListener('resize', resizeCanvas);