其他
【每日一练】44—绘图应用程序效果的实现
写在前面
鼠标绘制这个功能,在很多绘画APP上,或者一些小工具上,也是非常常见的一个功能,比方我们电脑里自带的绘图小工具,虽然,今天这个小练习,是一个非常的简单的效果,没有那么多复杂的功能,但是,任何一个产品都是从小到大的。
因此,今天我们就先来练习一个简单的绘制功能效果,具体的看下图:
关于它的实现源码,请看后面的内容,我都将源码放在文章里了。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>【每日一练】44—绘图应用程序效果的实现</title>
</head>
<body>
<canvas id="canvas" width="800" height="700"></canvas>
<div class="toolbox">
<button id="decrease">-</button>
<span id="size">10</span>
<button id="increase">+</button>
<input type="color" id="color">
<button id="clear">X</button>
</div>
</body>
</html>
* {
box-sizing: border-box;
}
body {
background-color: #f5f5f5;
font-family: 'Roboto', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
canvas {
border: 2px solid #00a6bc;
}
.toolbox {
background-color: #00a6bc;
border: 1px solid #00a6bc;
display: flex;
width: 804px;
padding: 1rem;
}
.toolbox > * {
background-color: #fff;
border: none;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 2rem;
height: 50px;
width: 50px;
margin: 0.25rem;
padding: 0.25rem;
cursor: pointer;
}
.toolbox > *:last-child {
margin-left: auto;
}
const canvas = document.getElementById('canvas');
const increaseBtn = document.getElementById('increase');
const decreaseBtn = document.getElementById('decrease');
const sizeEL = document.getElementById('size');
const colorEl = document.getElementById('color');
const clearEl = document.getElementById('clear');
const ctx = canvas.getContext('2d');
let size = 10
let isPressed = false
colorEl.value = 'black'
let color = colorEl.value
let x
let y
canvas.addEventListener('mousedown', (e) => {
isPressed = true
x = e.offsetX
y = e.offsetY
})
document.addEventListener('mouseup', (e) => {
isPressed = false
x = undefined
y = undefined
})
canvas.addEventListener('mousemove', (e) => {
if(isPressed) {
const x2 = e.offsetX
const y2 = e.offsetY
drawCircle(x2, y2)
drawLine(x, y, x2, y2)
x = x2
y = y2
}
})
function drawCircle(x, y) {
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2)
ctx.fillStyle = color
ctx.fill()
}
function drawLine(x1, y1, x2, y2) {
ctx.beginPath()
ctx.moveTo(x1, y1)
ctx.lineTo(x2, y2)
ctx.strokeStyle = color
ctx.lineWidth = size * 2
ctx.stroke()
}
function updateSizeOnScreen() {
sizeEL.innerText = size
}
increaseBtn.addEventListener('click', () => {
size += 5
if(size > 50) {
size = 50
}
updateSizeOnScreen()
})
decreaseBtn.addEventListener('click', () => {
size -= 5
if(size < 5) {
size = 5
}
updateSizeOnScreen()
})
colorEl.addEventListener('change', (e) => color = e.target.value)
clearEl.addEventListener('click', () => ctx.clearRect(0,0, canvas.width, canvas.height))
写在最后
以上就是每日一练的全部内容,希望今天的小练习对你有用,如果你觉得有帮助的话,请点赞我,关注我,并将它分享给你身边做开发的朋友,也许能够帮助到他。
我是杨小爱,我们明天见。
学习更多技能
请点击下方公众号