canvas {
border: 1px solid #ccc;
}
var canvas = document.getElementById('canvas')
var context = canvas.getContext('2d')
var drawing = false
var color = '#000000'
var undoStack = []
var brushSize = 10
var brushType = 'round'
var eraserEnabled = false
canvas.addEventListener('mousedown', startDrawing)
canvas.addEventListener('mousemove', draw)
canvas.addEventListener('mouseup', stopDrawing)
canvas.setAttribute('width', 1000)
canvas.setAttribute('height', 500)
var colorInput = document.getElementById('color')
colorInput.addEventListener('change', function () {
color = colorInput.value
eraserEnabled = false
})
var clearButton = document.getElementById('clear')
clearButton.addEventListener('click', function () {
context.clearRect(0, 0, canvas.width, canvas.height)
undoStack = []
})
var undoButton = document.getElementById('undo')
undoButton.addEventListener('click', function () {
if (undoStack.length > 0) {
context.clearRect(0, 0, canvas.width, canvas.height)
undoStack.pop()
redraw()
}
})
var brushSizeInput = document.getElementById('brush-size')
brushSizeInput.addEventListener('change', function () {
brushSize = brushSizeInput.value
})
var brushTypeInput = document.getElementById('brush-type')
brushTypeInput.addEventListener('change', function () {
brushType = brushTypeInput.value
})
var eraserButton = document.getElementById('eraser')
eraserButton.addEventListener('click', function () {
eraserEnabled = true
})
function startDrawing(event) {
drawing = true
context.beginPath()
context.moveTo(event.offsetX, event.offsetY)
}
function draw(event) {
if (drawing) {
if (eraserEnabled) {
context.globalCompositeOperation = 'destination-out'
context.strokeStyle = 'rgba(0,0,0,1)'
context.lineWidth = brushSize
context.lineCap = brushType
} else {
context.globalCompositeOperation = 'source-over'
context.strokeStyle = color
context.lineWidth = brushSize
context.lineCap = brushType
}
context.lineTo(event.offsetX, event.offsetY)
context.stroke()
}
}
function stopDrawing() {
drawing = false
undoStack.push(canvas.toDataURL())
}
function redraw() {
var img = new Image()
img.onload = function () {
context.drawImage(img, 0, 0)
}
img.src = undoStack[undoStack.length - 1]
}
加入视频功能以后的涂鸦板