greenn
greenn

Reputation: 309

Change width of canvas using css

I am using this JavaScript signature pad that I found in code pen. I can set the width of the canvas using HTML

<canvas id="signature-pad" width="600" height="200"></canvas>

I can change the width as much as I want. However, when I change the width using CSS like width:80vw even though the canvas width increases I can either no longer sign in there or the mouse pointer and the pointer for the signature is at a different place. I don't know how to fix this.

Upvotes: 0

Views: 2805

Answers (2)

likle
likle

Reputation: 1797

You could add something like this to the constructor of your SignaturePad (codepen fork):

    canvas.width = canvas.scrollWidth;
    canvas.height = canvas.scrollHeight;
    window.addEventListener('resize', function() {
      canvas.width = canvas.scrollWidth;
      canvas.height = canvas.scrollHeight;
    });

The calculations of the mouse position only work correctly if your canvas drawing width and height is equal to the canvas element width and height.

Upvotes: 3

Tomasz Bubała
Tomasz Bubała

Reputation: 2153

Problem

width and height attributes on canvas element specify the amount of pixels you can draw on. By using CSS to make your canvas bigger you just stretch your 600x200 canvas to make it appear bigger.

How to fix this?

Use height and width attributes to resize your canvas the way you expect - with JavaScript, for example on resize event.

Upvotes: 1

Related Questions