【问题标题】:Resize function for HTML5 CanvasHTML5 Canvas 的调整大小功能
【发布时间】:2015-05-03 23:00:39
【问题描述】:

我设法组合了一个动态调整大小的 HTML5 Canvas,但它有问题。例如,它只缩放高度,而不是宽度。我的画布宽度为900px,高度为850px。另一个问题是它也扩大了画布,远远超出了定义的宽度和高度。

我做错了什么?

到目前为止,这是我尝试过的:

var canvas, stage, exportRoot;

function init() {
  createjs.MotionGuidePlugin.install();

  canvas = document.getElementById("canvas");
  exportRoot = new lib.Hat_finale();

  stage = new createjs.Stage(canvas);
  stage.addChild(exportRoot);
  stage.update();

  createjs.Ticker.setFPS(24);
  createjs.Ticker.addEventListener("tick", stage);
}

function resize() {
  var height = window.innerHeight;

  var ratio = canvas.width / canvas.height;
  var width = height * ratio;

  canvas.style.width = width + 'px';
  canvas.style.height = height + 'px';
}

window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
#container {
  margin: 0 auto;
  max-width: 900px;
  max-height: 850px;
}
<div id="container">
  <canvas id="canvas" width="900" height="850" style="background-color:#ffffff"></canvas>
</div>

更新:

如果我尝试@havex 所说的,像这样更改属性:canvas.width = width;canvas.height = height; 而不是 canvas.style.width = width+'px';canvas.style.height = height+'px'; 我得到的是一个可调整大小的框,但不是动画。参考图片:

【问题讨论】:

  • @halex 它不起作用,它只缩放某种盒子而不是整个动画,请参阅问题更新以获取参考照片。
  • @gamealchemist 你这是什么意思??
  • @gamealchemist 发布一个答案,如果它很好并且有效,你会得到标记的答案^^谢谢

标签: javascript html canvas


【解决方案1】:

我无法解释为什么会发生这种情况,因为现在是凌晨 4:30,我还没有睡觉,但是更改这些,它应该可以工作(您可以删除边框):

HTML

<div id="container">
<canvas id="canvas" style="background-color:#ffffff"></canvas>
</div>

CSS

#container{
  margin:0 auto;
  width:900px;
  height:850px;
  border: 1px solid black;
}

canvas { width: 900px; height: 850px; border: 1px solid red; }

http://jsfiddle.net/Ln5z1zab/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2013-04-14
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多