Džuris
Džuris

Reputation: 2234

How to increase canvas length?

In my javascript application I have a function that increases or decreases the length (height) of the content by a set amount (let's say 150px). Currently I just create sufficiently large canvas and use the amount that I need. Obviously I'll eventually run out of space in this manner.

I can think of some solutions, but they all have their drawbacks and I don't know which would be better:

  1. Adding a scroller in the canvas. No idea how that works though.
  2. Resizing the canvas height. I would need to redraw the picture every time.
  3. Adding or destroying a new div with a new canvas.

What would be the best solution in such case?

Upvotes: 2

Views: 161

Answers (1)

markE
markE

Reputation: 105015

You can keep enlarging your canvas forever, just let the user navigate you image with scrollbars

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/Cgrcs/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; padding:50px; }
    canvas{border:1px solid red;}
    div{ overflow:scroll; width:300px; height:300px; border:2px solid blue; }
</style>

<script>
$(function(){

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

    var img=new Image();
    img.onload=function(){
      ctx.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
    }
    img.src="http://us.123rf.com/400wm/400/400/leungchopan/leungchopan1202/leungchopan120200432/12559267-singapore-cityscape.jpg";


}); // end $(function(){});
</script>

</head>

<body>
    <div>
            <canvas id="canvas" width=800 height=500></canvas>
    </div>
</body>
</html>

Upvotes: 2

Related Questions