Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

HTML5 Canvas and mouse events issue

HTML5 Canvas and mouse events issue

Problem

I'm trying to have a HTML5 page that includes a customer signature box. This would be used on tablets for the most part. This is done with a Canvas element, and JavaScript events on the mouse.

Issue 1: The Y portion works perfectly, but the X portion will ONLY work if I set my canvas with to 300. If the width is 500, then the X portion is correct at x-coord 0. When the user draws to x-coord 300, the line on the screen is now at the 500px mark on the canvas. NOWHERE in my code do I set anything to 300px, so I just don't get what's up.

Issue 2: I have code to stop scrolling on tablets and allow the user to sign in the canvas (see "prevent" var in JavaScript). That does not work at all.

HTML:

CSS: (Makes the width 100% up to 500px, and always 150px high)

#canvasDiv
{
   float: left;
   width: 100%;
   height: 150px;
   max-width: 500px;
}

#canvasSignature
{
   width: 100%;
   height: 100%;
   background-color: #F0F0F0;
   border: 1px solid Black;
   cursor: crosshair;
}

JavaScript:

Problem courtesy of: Paul

Solution

#canvasSignature
{
   width: 100%;
   height: 100%;
   background-color: #F0F0F0;
   border: 1px solid Black;
   cursor: crosshair;
}

This is no good! As a rule of thumb you never want to change the CSS width/height of a canvas.

You are literally stretching a canvas sized 300x150 to skew across the entire screen. This is probably the source of 99% of your mouse problems.

The reason is seems fine in the y-direction is purely coincidence: The canvas is by default 300x150 and you have a div that is 150 high, so there is no skewing by the CSS. But if you wanted the div to be 200 high you'd see the problem there too!

You need to set the Canvas height and width as attributes and not as CSS properties:

Or else in JavaScript:

var can = document.getElementById('canvasSignature');
can.width = 500;
can.height = 150;

It looks like you want to have the canvas width change dynamically. This is OK, but you have to do one of a few things. One would be to use the window's onresize event, and set the canvas width equal to the div's clientWidth every time this happens (if the clientWidth has changed of course). The other would be to do a simple general timer to check for the same thing every half-second or so.


Note that I did not check the validity of your getPosition function. There might be other errors there that may be a separate issue, but its probably OK.

Solution courtesy of: Simon Sarris

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

HTML5 Canvas and mouse events issue

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×