<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="toolbar">
<button class="pencil">pencil</button>
<button class="eraser">eraser</button>
<input class="inputText" type="text" placeholder="请输入文本">
<button class="text">text</button>
<button class="fillColor">fillCo</button>
</div>
<canvas class="mycanvas" width="400" height="300"></canvas>
<script>
const canvas = document.querySelector('.mycanvas')
const ctx = canvas.getContext('2d')
const canvasBackgroundColor = '#aaa'
ctx.fillStyle = canvasBackgroundColor
ctx.fillRect(0,0,400,300)
const pencil = document.querySelector('.pencil')
pencil.addEventListener('click', pencilTool, false)
const eraser = document.querySelector('.eraser')
eraser.addEventListener('click', eraserTool, false)
const textBtn = document.querySelector('.text')
textBtn.addEventListener('click', textTool, false)
const fillCoBtn = document.querySelector('.fillColor')
fillCoBtn.addEventListener('click', fillColorTool, false)
function draw(strokeStyle){
canvas.onmousedown = (e) => {
const x1 = e.clientX - canvas.offsetLeft
const y1 = e.clientY - canvas.ofsfsetTop
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(x1, y1)
canvas.onmousemove = (e) => {
const x2 = e.clientX - canvas.offsetLeft
const y2 = e.clientY - canvas.offsetTop
ctx.lineTo(x2, y2)
ctx.strokeStyle = strokeStyle
ctx.stroke()
}
canvas.onmouseup = () => {
ctx.closePath()
canvas.onmousemove = canvas.onmouseup = null
}
}
}
function pencilTool(){
let strokeStyle = '#fff'
draw(strokeStyle)
}
function eraserTool(){
let strokeStyle = canvasBackgroundColor
draw(strokeStyle)
}
function getInputText(){
return document.querySelector('.inputText').value
}
function textTool(){
// 清除鼠标事件
canvas.onmousedown = null
const inputText = getInputText()
canvas.onmouseup = (e) => {
const x = e.clientX - canvas.offsetLeft
const y = e.clientY - canvas.offsetTop
ctx.font = "10px serif"
ctx.fillStyle = '#000'
if (inputText){
ctx.fillText(inputText, x, y)
} else {
alert('请输入文本')
}
}
}
function fillColorTool(){
canvas.onmouseup = (e) => {
console.log('fillColor')
}
}
</script>
</body>
</html>
canvas 画笔、橡皮擦和文本输入
最新推荐文章于 2024-05-17 16:35:16 发布