使画布高度自动

2023-11-29

我有画布

<canvas id="canvas" width="1700" height="679" style="background-color:#ffffff;width:100%;overflow:hidden;margin-top: -7px;"></canvas>

它在 Chrome 和 Firefox 上运行良好。但是,ie 只能使用宽度:100%,但不能更改高度(679 上的高度)

我尝试将高度设置为自动且 100%,但情况越来越糟

编辑:终于!我得到了它。 确实,画布内容在宽度 100% 时效果不佳。 然而,对于高度(IE9以上是工作)你必须设置高度样式

$("#canvas").attr('style','background-color:#ffffff; width:100%;height:679px;overflow:hidden;margin-top: -7px;');

并使用 Jquery 重新调整画布大小

function resizeIE()
{
  canvas = document.getElementById("canvas");
  if($.browser.msie) //only IE
  {
    $("#canvas").attr('style','background-color:#ffffff; width:100%;height:679px;overflow:hidden;margin-top: -7px;');
//set the height style first

    if(window.innerWidth<960) //for other device (only for me)
    {
      var height_ie = (window.innerWidth*39.941176470588235294117647058824)/100;
      //to make the ratio of canvas find the pencentage
      //ex. canvas height: 1700px canvas width: 679px;
      //(679*100)/1700 = 39.941 <-- use this one
      //best solution
    }
    else
    {
      var height_ie = window.innerHeight-160; //just for the logo for my web
    }
    canvas.style.height = height_ie+"px";
 }
}

调整窗口大小适用于 document.ready

window.onresize = function(event) {
  resizeIE();
};

如果您使用 CSS 调整画布大小,您实际上是在重塑画布的视口。

将此视为缩放图像。就像调整 .jpg 图像大小一样,您可能会出现像素化和失真现象。

相反,调整画布元素的大小。

将此视为向画布的宽度和高度添加更多空像素,而不是“拉伸”现有像素。

以下是如何向 canvas 元素添加像素以使其 100% 占据浏览器窗口:

var canvas=getElementById("myCanvas");
canvas.width= window.innerWidth;
canvas.height=window.innerHeight;

如果您要调整浏览器窗口的大小,可以将此代码放入窗口调整大小处理程序中以使其自动发生。

注意:每当您以这种方式调整画布大小时,都必须重新绘制画布内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使画布高度自动 的相关文章