Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "react-sketchpad",
"version": "0.0.3",
"description": "Sketch pad created with canvas",
"main": "index.js",
"main": "lib/index.js",
"scripts": {
"prepublish": "npm run lint && npm run build",
"build": "babel ./src -d ./lib --ignore '__tests__'",
Expand Down
46 changes: 41 additions & 5 deletions src/SketchPad.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,13 @@ export default class SketchPad extends Component {
constructor(props) {
super(props);
this.initTool = this.initTool.bind(this);
this.useTouch = 'ontouchstart' in window;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you move this into getCursorPosition, so instead here it would be there like if(!!window.ontouchstart) { ... }

this.onTouchStart = this.onMouseDown.bind(this);
this.onMouseDown = this.onMouseDown.bind(this);
this.onTouchMove = this.onMouseMove.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onDebouncedMove = this.onDebouncedMove.bind(this);
this.onTouchEnd = this.onMouseUp.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
}

Expand Down Expand Up @@ -103,11 +107,40 @@ export default class SketchPad extends Component {
}

getCursorPosition(e) {
const {top, left} = this.canvas.getBoundingClientRect();
return [
e.clientX - left,
e.clientY - top
];
if (this.useTouch) {

// touchstart
if (!this.clientBounds) {

// TODO: consider an option to refresh this value on scroll? window resize?
this.clientBounds = this.canvas.getBoundingClientRect();
}
const {top, left} = this.clientBounds;
let x, y;

// touchend
if (!e.touches || !e.touches[0]) {
let touch = this.lastTouch;
this.lastTouch = null;
return touch;
}

// touchmove
const {clientX, clientY} = e.touches[0];
x = clientX - left;
y = clientY - top;
this.lastTouch = [x, y];
return [
x,
y
];
} else {
const {top, left} = this.canvas.getBoundingClientRect();
return [
e.clientX - left,
e.clientY - top
];
}
}

render() {
Expand All @@ -120,6 +153,9 @@ export default class SketchPad extends Component {
onMouseMove={this.onMouseMove}
onMouseOut={this.onMouseUp}
onMouseUp={this.onMouseUp}
onTouchStart={this.onTouchStart}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we just pass down mouse event? like onTouchStart={this.onMouseDown} we don't need to create separate logic then in constructor

onTouchEnd={this.onTouchEnd}
onTouchMove={this.onTouchMove}
width={width}
height={height}
/>
Expand Down