如果它扩展Canvas限制区域,就会变得不可见,想要在画布区域内滚动以使隐形的东西可见

时间:2014-05-17 10:49:43

标签: html5-canvas

我希望有一种滚动类型的东西可见,这些部分超出画布限制并变得不可见。

这是我的代码:

<html>
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,60);
ctx.fillStyle="#FFD000";
ctx.fillRect(150,0,50,100);

</script>

</body>
</html>

在我的代码中;存在红色矩形和黄色矩形。如果我可以让我的画布区域宽度更小,比如&#34;宽度=&#34; 150&#34; &#34; ;不是200;然后黄色的盒子隐藏起来。

我想将myCanvas宽度保持为150;不是200(如代码中所述)并且想要看到黄色框(滚动画布或任何可能的方式)。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

如果您想将较大的画布放入较小的区域,您可以:

  • 将较大的画布包裹在div中,

  • 使用CSS将div调整为所需的比例,

  • 设置div的overflow属性以滚动

演示:http://jsfiddle.net/m1erickson/6RPGr/

enter image description here

<强> HTML

  <h4>Use scrollbars to view more of the canvas</h4>
  <div id="canvasWrapper">
      <canvas id="canvas" width=200 height=100></canvas>
  </div>

<强> CSS

  body{ background-color: ivory; padding:50px; }
  #canvasWrapper{ overflow:scroll; width:150px; height:100px; border:2px solid blue; }

<强>的JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,60);
ctx.fillStyle="#FFD000";
ctx.fillRect(150,0,50,100);

答案 1 :(得分:0)

感谢您的回复。我不希望宽度为200.如果我给出200宽度,那么肯定会看到黄色框。我希望宽度为150并水平滚动以查看黄色框。这样,如果我在画布中添加一些新的颜色框,我不需要每次都调整原始画布大小。通过滚动我可以看到新项目,即使这些超过画布原始限制。

这个优化代码不符合我的上述期望,

<html>

<head>  
<style>
body{ background-color: ivory; padding:50px; }
#canvasWrapper{ overflow:scroll; width:150px; height:100px; border:2px solid blue; }
</style>
</head>
<body>
<div id="canvasWrapper">
<canvas id="myCanvas" width="150" height="100" style="border:1px solid #c3c3c3;">
</canvas>
</div>
<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0,0,150,60);
ctx.fillStyle="#FFD000";
ctx.fillRect(150,0,50,100);

</script>
</body>
</html>
相关问题