Chris R
Chris R

Reputation: 21

How to resize the drawing of the canvas in HTML5?

I would like to resize the canvas to a smaller dimension than what it is. Here is my code:

             var modelPane = document.getElementById('model_pane');


        //create canvasclass="modelview"
        var canvas_ = document.createElement('canvas');
        canvas_.setAttribute('width', 1160);
        canvas_.setAttribute('height', 500);
        canvas_.setAttribute('id', 'canvas');
        canvas_.setAttribute('class', 'modelview');
        var ctx_ = canvas_.getContext('2d');

        //draw
        for (i=0;i<nodes.length;i++)
                            {
            ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);


    }

        //scale
        ctx_.scale(0.3,0.3);
    modelPane.appendChild(canvas_);

Yet this doesn't work. Anyone know why? The canvas doesn't resize to the new dimensions.

Upvotes: 2

Views: 2185

Answers (1)

Joe
Joe

Reputation: 82604

You need to call scale first:

var ctx_ = canvas_.getContext('2d');
ctx_.scale(0.3,0.3);
//draw
for (i=0;i<nodes.length;i++)
    ctx_.strokeRect(nodes[i].x,  nodes[i].y, nodes[i].width, nodes[i].height);
}

Think about it, like you need to scale you canvas down. Then draw on the smaller canvas. Example

Upvotes: 1

Related Questions