Tyler Crompton
Tyler Crompton

Reputation: 12652

Drawing on the canvas with a "pencil"

I made a script that draws a series of lines on a canvas that makes it look like a sketch. There are two issues with the script. One, why is the y value twice as much as it should be? And two, why is the line several pixels wide and faded out?

I've tried it in both Google Chrome and Firefox and I get the same incorrect results. I realize that I can divide the y value by two to fix the first problem but that part of my question is why do I need to do that. I shouldn't have to.

Upvotes: 4

Views: 3481

Answers (2)

Cystack
Cystack

Reputation: 3551

Give a width and a height to your canvas; always ! http://jsfiddle.net/mz6hK/7/

fixed

Upvotes: 1

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

I think you have two issues:

  1. You need to be more careful in how you calculate the offset of where to draw. I have some code below that demonstrates how to handle this properly.
  2. You aren't setting the width and height on the <canvas> element itself, which means it will scale your lines in funny ways depending how what you've set in your css.

An Example

I built a simple collaborative drawing app using <canvas> and socket.io that lets you draw to the screen like a pencil. You can check it out here:

http://xjamundx.no.de/

The source is also on github if that might help:

In particular I do something like this to figure out where to draw things:

x = e.clientX + window.scrollX
y = e.clientY + window.scrollY
x -= $game.offsetLeft
y -= $game.offsetTop

Upvotes: 2

Related Questions