Diane2
Diane2

Reputation: 160

resize HTML5 canvas

I am using an html canvas element to draw some data as a chart.

I have 4 canvases on one page with a chart in each of them.

When the user clicks on a chart I want to enlarge the chart.

For the smaller charts, my code is as follows: <canvas width='350' height='200' ></canvas>

For the larger charts, I rebuild the same chart with the following attributes: <canvas width='700' height='350' ></canvas>

I have tried:

  1. onclick - redraw the entire chart with new values in the height and width attributes.

  2. onclick - redraw the entire chart with new values in the css styles height and width.

  3. onclick - redraw the entire chart with new values in both attributes and css styles.

I am getting very unexpected results such as a blank chart, or bigger canvas but the proportions are way off.

Upvotes: 1

Views: 4321

Answers (2)

Joe Marie
Joe Marie

Reputation: 346

is this what you want? i made a jsfiddle check it here http://jsfiddle.net/NDgMC/ , I just used :checked pseudo element in css and a checkbox

HTML code:

<input type="checkbox" class="toggle" name="ao-toggle" />
<canvas id="myCanvas"></canvas>

CSS code:

input.toggle{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    margin: 0;
    padding: 0;
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
    opacity: 0;
    z-index: 100;
    border: none;
    cursor: pointer;
}

input.toggle:checked + #myCanvas{
    border:1px solid #000000;
    background-color:#000;
    width:400px;
    height:200px;
    -webkit-transition:0.5s;
    transition:0.5s;
}

#myCanvas{
    border:1px solid #000000;
    background-color:#ccc;
    width:200px;
    height:100px;
    -webkit-transition:0.5s;
    transition:0.5s;
}

Upvotes: 0

markE
markE

Reputation: 105035

Save the starting canvas dimensions:

var canvasWidth=canvas.width;
var canvasHeight=canvas.height;

To enlarge:

canvas.width=canvasWidth*1.5;
canvas.height=canvasHeight*1.5;
context.scale(1.5,1.5);
// And now redraw your chart normally
// It will be 50% larger

To reduce back to starting dimensions:

canvas.width=canvasWidth;
canvas.height=canvasHeight;
context.scale(1,1);
// And now redraw your chart normally
// It will be back to the starting dimensions

Then when the canvas is clicked, toggle the dimensions between larger and starting sizes.

Upvotes: 4

Related Questions