const canvas = document.createElement('canvas')
canvas.width = 400
canvas.height = 400
canvas.className = 'main_canvas'
document.body.appendChild(canvas)
const ctx = canvas.getContext('2d')
const info = {
offset: {x: 0, y: 0},
scale: 1,
scaleStep: 0.1,
minScale: 0.5,
maxScale: 2
}
// 獲取鼠標(biāo)在canvas畫(huà)布上的坐標(biāo)
const getCanvasPostion = (e) => {
return {
x: e.offsetX,
y: e.offsetY,
}
}
//計(jì)算呢兩點(diǎn)之間的距離
const getDistance = (p1, p2) => {
return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2)
}
//更新畫(huà)布
const updateCanvas = () => {
const backgroundImage = new Image() // 創(chuàng)建Image對(duì)象
backgroundImage.src = 'https://ts1.cn.mm.bing.net/th/id/R-C.66d7b796377883a92aad65b283ef1f84?rik=sQ%2fKoYAcr%2bOwsw&riu=http%3a%2f%2fwww.quazero.com%2fuploads%2fallimg%2f140305%2f1-140305131415.jpg&ehk=Hxl%2fQ9pbEiuuybrGWTEPJOhvrFK9C3vyCcWicooXfNE%3d&risl=&pid=ImgRaw&r=0' //設(shè)置圖片路徑
backgroundImage.onload = function(){
console.log('圖片加載完成');
ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height) //繪制背景圖片
}
}
updateCanvas()
//監(jiān)聽(tīng)滾輪滾動(dòng)縮放畫(huà)布
canvas.addEventListener('wheel', (e) => {
e.preventDefault()
ctx.clearRect(0, 0, canvas.width, canvas.height)
const canvasPosition = getCanvasPostion(e) //獲取畫(huà)布上的事件坐標(biāo)
console.log(canvasPosition)
const realCanvasPosition = { //鼠標(biāo)在畫(huà)布上的坐標(biāo)
x: canvasPosition.x - info.offset.x,
y: canvasPosition.y - info.offset.y
}
// 放縮時(shí)產(chǎn)生的偏移量
const deltaX = realCanvasPosition.x / info.scale * info.scaleStep
const deltaY = realCanvasPosition.y / info.scale * info.scaleStep
if (e.wheelDelta > 0 && info.scale < info.maxScale) {
console.log('上滾');
info.offset.x -= deltaX
info.offset.y -= deltaY
info.scale += info.scaleStep
}else if (e.wheelDelta <= 0 && info.scale > info.minScale){
console.log('下滾');
info.offset.x += deltaX
info.offset.y += deltaY
info.scale -= info.scaleStep
}
ctx.setTransform(info.scale, 0, 0, info.scale, info.offset.x, info.offset.y)
updateCanvas()
})
canvas實(shí)現(xiàn)鼠標(biāo)滾輪滾動(dòng)縮放畫(huà)布效果文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-758878.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-758878.html
到了這里,關(guān)于canvas實(shí)現(xiàn)鼠標(biāo)滾輪滾動(dòng)縮放畫(huà)布的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!