px-brush
v1.0.1
Published
Pixelated Brush/Eraser on HTML5 Canvas
Downloads
805
Maintainers
Readme
PxBrush
Pixelated Brush on HTML5 Canvas
Getting started
npm install --save px-brush
oryarn add px-brush
import PxBrush from 'px-brush'
const pxBrush = new PxBrush(canvas)
- call
draw
orerase
function like below
const canvas = document.createElement('canvas')
const pxBrush = new PxBrush(canvas)
const size = 10
const color = '#0000ff' // blue
let mouseDown = false
let startPosition = null
const getPosition = (canvas, event) => {
const rect = canvas.getBoundingClientRect()
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
}
canvas.addEventListener('mousedown', () => {
mouseDown = true
startPosition = getPosition(canvas, event)
pxBrush.draw({
from: startPosition,
to: startPosition,
size,
color
})
})
canvas.addEventListener('mousemove', (event) => {
if (!mouseDown) { return }
const position = getPosition(canvas, event)
pxBrush.draw({
from: startPosition,
to: position,
size,
color
})
startPosition = position
})
canvas.addEventListener('mouseup', () => {
mouseDown = false
})