在学习JavaScript的过程中接触到了canvas,初步学习了一下canvas,跟着教学视频练习了几个小案例。
<canvas></canvas>在js中用于提供画布,然后通过js在这个画布上面作画
我着重练习了以下几个小案例
(如果敲代码过程中没有提示字的话,在获取canvas元素之前写一行代码:
/** @type {HTMLCanvasElement} */
1.棋盘
const cvs = document.querySelector('.canvas')
const cxt = cvs.getContext('2d')
const rectSize = 50
const xNum = Math.floor(cvs.width / rectSize)
const yNum = Math.floor(cvs.height / rectSize)
for(let i = 0; i < xNum; i++) {
for(let j = 0; j < yNum; j++) {
if(j % 2) {
if(i % 2) {
cxt.fillStyle = '#53a0e9'
cxt.fillRect(i * rectSize, j * rectSize, rectSize, rectSize)
} else {
cxt.fillStyle = '#363636'
cxt.fillRect(i * rectSize, j * rectSize, rectSize, rectSize)
}
} else {
if(i % 2) {
cxt.fillStyle = '#363636'
cxt.fillRect(i * rectSize, j * rectSize, rectSize, rectSize)
} else {
cxt.fillStyle = '#53a0e9'
cxt.fillRect(i * rectSize, j * rectSize, rectSize, rectSize)
}
}
}
}
2.加载圆环
圆环加载时,外圈的蓝色环会动,中间的数据也会变化
/** @type HTMLCanvasElement */
const cvs = document.querySelector('.canvas')
const cxt = cvs.getContext('2d')
// 设置canvas的宽高等于视口的宽高
cvs.width = window.innerWidth
cvs.height = window.innerHeight
const midx = cvs.width / 2
const midy = cvs.height / 2
function outerArc() {
cxt.beginPath()
cxt.fillStyle = '#ff9900'
cxt.strokeStyle = '#00d8ff'
cxt.lineWidth = 20
cxt.arc(midx, midy, 100, 0, 2 * Math.PI)
cxt.fill()
cxt.stroke()
}
let angle = 0
function ring() {
cxt.beginPath()
cxt.strokeStyle = '#434343'
cxt.lineWidth = 20
cxt.arc(midx, midy, 100, 0, angle * (Math.PI / 180))
cxt.stroke()
angle ++
// 加载文本
const text = `${Math.floor(angle * 100 / 360)}%`
cxt.font = '32px 微软雅黑'
cxt.fillStyle = 'black'
cxt.textBaseline = 'middle'
cxt.textAlign = 'center'
cxt.fillText(text, midx, midy)
}
function play() {
if(angle === 361) return
cxt.clearRect(0, 0, cvs.width, cvs.height)
outerArc()
ring()
window.requestAnimationFrame(play)
}
play()
3.放大镜
导入图片,鼠标点击后移动光标附近有放大效果,鼠标松开后复原
const cvs = document.querySelector('.canvas')
const cxt = cvs.getContext('2d')
cvs.width = window.innerWidth
cvs.height = window.innerHeight
const img = new Image()
img.src = 'images/pdf.png'
img.onload = function() {
cxt.drawImage(img, 0, 0)
}
const handleMove = function(e) {
cxt.clearRect(0, 0 , cvs.width, cvs.height)
cxt.drawImage(img, 0, 0)
const movex = e.clientX - cvs.offsetLeft
const movey = e.clientY - cvs.offsetTop
cxt.drawImage(img, movex - 40, movey-40, 80, 80, movex-80, movey-80, 160, 160)
}
cvs.addEventListener('mousedown', function(e) {
const x = e.clientX - cvs.offsetLeft
const y = e.clientY - cvs.offsetTop
cxt.beginPath()
cxt.moveTo(x, y)
document.addEventListener('mousemove', handleMove)
})
cvs.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', handleMove)
cxt.drawImage(img, 0 , 0)
})
主要通过这三个案例练习使用canvas的一些方法,比如:moveTo()、lineTo()、fillRect()、stroke()、drawImage()、fillText()……