Skip to content

Instantly share code, notes, and snippets.

@calmery
Last active Jan 8, 2018
Embed
What would you like to do?
Hyperapp
<!DOCTYPE html>
<html>
<head>
<script src="hyperapp.js"></script>
<script>
// State
const state = {
x: null,
y: null,
color: '#000',
context: null,
isShow: false,
isDraw: false
}
// Actions
const setupCanvas = ( element, actions ) => {
element.addEventListener( 'mousemove', e => {
const rect = e.target.getBoundingClientRect()
const x = e.clientX - rect.left
const y = e.clientY - rect.top
actions.draw( { x, y } )
} )
element.addEventListener( 'mouseout', _ => actions.setPosition( { x: null, y: null } ) )
element.addEventListener( 'mousedown', _ => actions.setIsDraw( true ) )
element.addEventListener( 'mouseup', _ => actions.setIsDraw( false ) )
return ( { context: element.getContext( '2d' ) } )
}
const actions = {
draw: ( { x, y } ) => ( state, actions ) => {
if( state.isDraw ){
const context = state.context
context.beginPath()
context.moveTo( state.x || x, state.y || y )
context.lineTo( x, y )
context.lineCap = 'round'
context.lineWidth = 5
context.strokeStyle = state.color
context.stroke()
}
return actions.setPosition( { x, y } )
},
setColor: color => _ => ( { color: color } ),
setIsDraw: flag => _ => ( { isDraw: flag } ),
setIsShow: flag => _ => ( { isShow: flag } ),
setPosition: position => _ => position,
setContext: element => ( _, actions ) => setupCanvas( element, actions ),
unsetContext: _ => _ => ( { context: null } )
}
// View
const colors = {
black: '#000',
red: '#F00',
green: '#0F0',
blue: '#00F'
}
const createPalette = ( actions, colors ) =>
h( 'div', {}, Object.keys( colors ).map( color =>
h( 'button', { onclick: _ => actions.setColor( colors[color] ) }, color.charAt( 0 ).toUpperCase() + color.slice( 1 ) )
) )
const createCanvas = ( state, actions ) =>
h( 'canvas', {
width: 700,
height: 400,
key: 'canvas',
oncreate: actions.setContext,
onremove: ( element, done ) => {
actions.unsetContext()
done()
},
} )
const createPaletteToggle = ( state, actions ) =>
h( 'button', {
onclick: _ => actions.setIsShow( !state.isShow ),
onremove: ( element, callback ) => {
console.log( callback )
console.log( 'asd' )
}
}, ( state.isShow ? 'Hide' : 'Show' ) + 'ToolBar' )
const view = ( state, actions ) =>
h( 'div'
, {}
, [ createPaletteToggle( state, actions )
, h( 'br' )
].concat( state.isShow ? createPalette( actions, colors ) : undefined )
.concat( createCanvas( state, actions ) )
)
// Main
onload = _ =>
app( state, actions, view, document.body )
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment