javascript30 | 08.彩虹画板 | Github爆火项目 | 30


简单修改了一下,看看效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
padding: 0;
margin: 0;
}
</style>
<title>彩虹笔绘画板</title>
</head>
<body>
<canvas id="draw"></canvas>
<script>
const canvas = document.querySelector('#draw')
const parent = canvas.parentElement
parent.style.overflow = 'hidden'
const ctx = canvas.getContext('2d')
// 开启抗锯齿
ctx.imageSmoothingEnabled = true
// 设置像素比例
const pixelRatio = window.devicePixelRatio || 1
canvas.width = window.innerWidth * pixelRatio
canvas.height = window.innerHeight * pixelRatio
// 设置画布大小 获取父元素的大小
canvas.style.width = parent.clientWidth + 'px'
canvas.style.height = parent.clientHeight + 'px'
// 设置画笔样式
ctx.strokeStyle = '#BADA55'
ctx.lineJoin = 'round'
ctx.lineCap = 'round'
ctx.lineWidth = 10
let mode = 'pen'
let isDrawing = false
let maxLineWidth = 10
let minLineWidth = 4
let lastX = 0
let lastY = 0
let hue = 0 // 色相 0-360
let speed = 0
function draw(e) {
if (!isDrawing) return
if (mode === 'mouse') {
const x = e.clientX
const y = e.clientY
// 计算鼠标速度
speed = Math.sqrt(Math.pow(x - lastX, 2) + Math.pow(y - lastY, 2)) / 5
if (speed < 1) speed = 1
ctx.lineWidth = maxLineWidth / speed + minLineWidth
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`
ctx.beginPath()
ctx.moveTo(lastX * pixelRatio, lastY * pixelRatio)
ctx.lineTo(x * pixelRatio, y * pixelRatio)
ctx.stroke()
lastX = x
lastY = y
}
if (mode === 'pen') {
const x = e.touches[0].clientX
const y = e.touches[0].clientY
ctx.lineWidth = maxLineWidth * e.touches[0].force + minLineWidth
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`
ctx.beginPath()
ctx.moveTo(lastX * pixelRatio, lastY * pixelRatio)
ctx.lineTo(x * pixelRatio, y * pixelRatio)
ctx.stroke()
lastX = x
lastY = y
}
hue += 0.1
if (hue >= 360) {
hue = 0
}
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true
lastX = e.clientX - canvas.offsetLeft
lastY = e.clientY - canvas.offsetTop
})
canvas.addEventListener('mousemove', (e) => {
mode = 'mouse'
draw(e)
})
canvas.addEventListener('mouseup', () => {
isDrawing = false
ctx.lineWidth = maxLineWidth
})
canvas.addEventListener('touchstart', (e) => {
isDrawing = true
lastX = e.touches[0].clientX - canvas.offsetLeft
lastY = e.touches[0].clientY - canvas.offsetTop
})
canvas.addEventListener('touchmove', (e) => {
mode = 'pen'
draw(e)
})
canvas.addEventListener('touchend', () => {
isDrawing = false
ctx.lineWidth = maxLineWidth
})
</script>
</body>
</html>