Last active
August 29, 2015 14:15
-
-
Save ceane/e0b9d55b10f08b6d2a40 to your computer and use it in GitHub Desktop.
Listen to mouse cursor draw, really useful for canvas drawing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
// Before rendering run: | |
// React.initializeTouchEvents() | |
var Styles = { | |
WebKitUserSelect: 'none', | |
MozUserSelect: 'none', | |
MsUserSelect: 'none', | |
UserSelect: 'none', | |
cursor: 'pointer' | |
}; | |
export default class DrawListener extends React.Component { | |
constructor(props, context) { | |
this.state = { | |
active: false, | |
touchEnabled: this.isTouchEnabled() | |
}; | |
} | |
shouldComponentUpdate() { | |
return false; | |
} | |
render() { | |
this.activate = this.activate || this._changeActive(true); | |
this.deactivate = this.deactivate || this._changeActive(false); | |
var shouldRun = (e) => this.state.active && this.props.fn(e); | |
if (this.state.touchEnabled) return ( | |
<span | |
aria-label={label} | |
title={label} | |
className={this.props.className} | |
styles={!this.props.disableNoSelect && Styles} | |
onTouchStart={this.activate} | |
onTouchMove={shouldRun} | |
onTouchEnd={this.deactivate} | |
onTouchCancel={this.deactivate}> | |
{this.props.children} | |
</span> | |
); | |
return ( | |
<span | |
aria-label={this.props.label} | |
title={this.props.label} | |
className={this.props.className} | |
styles={!this.props.noStyle && Styles} | |
onMouseDown={this.activate} | |
onMouseMove={shouldRun} | |
onMouseUp={this.deactivate} | |
onMouseCancel={this.deactivate}> | |
{this.props.children} | |
</span> | |
); | |
} | |
static forceDeviceCheck(instance) { | |
var touchEnabled = instance.isTouchEnabled(); | |
instance.setState({ touchEnabled }, instance.forceUpdate); | |
} | |
isTouchEnabled() { | |
return 'ontouchstart' in window || | |
window.DocumentTouch && document instanceof DocumentTouch; | |
} | |
_changeActive(active) { | |
return (e) => { | |
if (this.props.onRelease && !active) this.props.onRelease(e); | |
this.setState({ active }); | |
} | |
} | |
} | |
DrawListener.defaultProps = { | |
label: 'Hold down your cursor and drag to draw' | |
}; | |
DrawListener.propTypes = { | |
className: React.PropTypes.string, | |
label: React.PropTypes.string, | |
noStyle: React.PropTypes.bool, | |
onDrawing: React.PropTypes.func.isRequired, | |
onRelease: React.PropTypes.func | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment