You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端屏幕旋转时Canvas坐标偏移问题

Fixing Canvas Drawing Coordinate Offset After Mobile Orientation Change

Hey Kunal, I’ve run into this exact headache before—let me break down why the coordinate offset is happening and how to fix it right away.

The Root Cause

Your current code only updates the CSS display size of the Canvas element using css(), but Canvas has two critical dimensions you need to sync up:

  • The CSS width/height: Controls how big the Canvas appears on the screen.
  • The Canvas element’s native width/height attributes: Defines the actual pixel grid that all drawing operations use under the hood.

When you resize via orientation change and only adjust the CSS size, you’re stretching the original pixel grid to fit the new display area. That’s why your image scales correctly (it’s just stretched with the CSS), but drawing coordinates get messed up—your tools are still mapping to the old, smaller pixel grid, not the new screen size.

The Fix

You need to update both the Canvas’s native pixel dimensions and its CSS size. Plus, we’ll account for mobile device pixel ratios (DPR) to avoid blurry drawing and ensure precise coordinate mapping:

$(window).resize(function () {
  const $canvas = $('#wPaint_181_17');
  const windowWidth = $(window).width();
  const windowHeight = $(window).height();
  
  // Handle high-DPI mobile screens (avoids blurry drawing)
  const dpr = window.devicePixelRatio || 1;
  
  // Update Canvas's native pixel grid to match display size * DPR
  $canvas[0].width = windowWidth * dpr;
  $canvas[0].height = windowHeight * dpr;
  
  // Set CSS display size to fit the window exactly
  $canvas.css({
    width: windowWidth + 'px',
    height: windowHeight + 'px'
  });
  
  // Sync with wPaint plugin: tell it to refresh internal coordinate calculations
  if ($canvas.data('wPaint')) {
    $canvas.wPaint('resize');
  }
});

Key Details to Remember

  • DPR Handling: Most modern mobile screens have a pixel ratio of 2x or 3x. Scaling the native Canvas size by DPR ensures your drawing stays sharp and coordinates align perfectly with taps.
  • wPaint Sync: Since you’re using the wPaint plugin, calling wPaint('resize') is crucial—it updates the plugin’s internal references to the Canvas, so its tools use the new coordinate system.
  • Initial Setup: Run this code once on page load too, not just on resize, to set the correct initial Canvas dimensions.

Quick Test

After applying this fix, rotate your device again: your image will still scale smoothly, and your drawing tools will now map directly to where you tap on the screen—no more offset!

内容的提问来源于stack exchange,提问作者kunal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:54:01