【问题标题】:Image gets distorted when using css to set canvas height/width 100%使用 css 将画布高度/宽度设置为 100% 时图像失真
【发布时间】:2016-02-24 22:21:24
【问题描述】:

我目前正在尝试将图像绘制到画布上,到目前为止我有这个:

"use strict";

var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');

function loadUI() {
   var topOverlay = new Image();
   topOverlay.src = "/images/00000999.png";
   topOverlay.onload = function() {
       ctx.drawImage(topOverlay, 0, 0, canvas.width, 10);
   }

   var bottomOverlay = new Image();
   bottomOverlay.src = "/images/00000998.png";

   if (debugging) {
    console.log('Drawing');
   }
}


loadUI();

效果很好,但是图像加载后看起来像这样:

什么时候应该是这样的:

好看的图片尺寸为800x40。

如果我删除了

canvas {
    width: 100%;
    height: 100%;
}

图像恢复正常,如何缩放画布?

任何信息都将非常感谢。

【问题讨论】:

标签: javascript canvas


【解决方案1】:

你没有考虑身高。当谈到高度/宽度与 clientHeight/clientWidth 时,Canvas 可能会令人困惑

创建画布时,css 宽度和高度与内部画布包含的像素数无关。除非特别设置,否则画布的宽度高度为 300x150。

我过去使用的一个技巧是使用 clientWidth 和比例来设置所有内容

"use strict";

var debugging = true;
var canvas = document.getElementById('astoniaCanvas');
var ctx = canvas.getContext('2d');

function loadUI() {
  var topOverlay = new Image();
  topOverlay.onload = function() {
   // use a scale between the image width and the canvas clientWidth  
    var scale = topOverlay.width / canvas.clientWidth;
    var newWidth = canvas.clientWidth;
    var newHeight = topOverlay.height * scale;
    // resize canvas based on clientWidth
    canvas.width = newWidth;
    canvas.height = newHeight;
    ctx.drawImage(topOverlay, 0, 0, newWidth, newHeight);
  }
  topOverlay.src = "http://i.stack.imgur.com/AJnjh.png";

  //  var bottomOverlay = new Image();
  //  bottomOverlay.src = "/images/00000998.png";

  if (debugging) {
    console.log('Drawing');
  }
}

loadUI()
<canvas id="astoniaCanvas" style="width: 100%"></canvas>

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2017-12-14
    • 2014-10-30
    • 1970-01-01
    • 2010-11-24
    相关资源
    最近更新 更多