眾所周知canvas是點陣圖,在點陣圖裡我們可以在裡面畫各種東西,可以是圖片,可以是線條等等。那我們想在canvas裡的某一張圖片中加入一個點擊事件該怎麼做到。而js只能監聽到canvas的事件,很明顯這張圖片是不存在與dom裡面的圖片只是畫在了canvas而已。下面我就來簡單的實作一個canvas內部各個圖片的事件綁定。
我先來講下實作原理:其實就是canvas綁定相關事件,在透過記錄圖片所在canvas的座標,判斷事件作用在哪個圖片中。這樣講是不是覺得跟事件代理有點相似。不過實現起來還是有稍許複雜的。
ps:下面的程式碼我是用ts寫的,大家當es6看就好了,稍有不同的可以查看
typescript的文檔(typescript真的很好用,建議大家多多了解)。
1.建立圖片和canvas之間的連結(這裡我用色塊來代替圖片)這裡要色塊和canvas建立一定的聯繫,而不是單純的渲染。還要記錄色塊所在座標、寬高。我們先一步一步來實現
首先寫基本的html頁面建立一個canvas:
<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width, initial-scale=1.0> <meta http-equiv=X-UA -Compatible content=ie=edge> <title>canvas事件</title> <style> html, body { height: 100%; background: #eee; } canvas { background: #fff; display: block; margin: 0 auto; } </style></head><body> <canvas width=500 height=500 id=canvas></canvas> </body>
下一步,我們要定一個Canvas的類,這個類別應該要有些什麼功能呢?
因為色塊也有自己的一些參數,為了方便拓展,我們也為色塊定一個類,這類需要的功能有:
寬、高、顏色、座標(x,y),還有Canvas實例;初步就定這幾個吧
ok開始寫
// Canvas類別 class Canvas { blockList: Block[] ctx: any canvas: any createBlock (option) { option.Canvas = this this.blockList.push(new Block(option)) this.painting() } rendering (block) { // 渲染色塊函數this.ctx.fillStyle = block.color this.ctx.fillRect(block.x, block.y, block.w, block.h) } painting () { // 將容器裡的色塊全部渲染到canvas // 清空畫布(渲染之前應該將老的清空) this.ctx.fillStyle = '# fff' this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height) this.blockList.forEach(ele => { this.rendering(ele) }) } constructor (ele) { // 初始化函數(輸入的是canvas) // 設定canvas this.canvas = ele this.ctx = this.canvas.getContext('2d') // 顏色塊容器this.blockList = [] }}class Block { w: number h: number x: number y: number color: string Canvas: Canvas hierarchy: number constructor ({ w, h, x, y, color, Canvas }) { // 初始化設定色塊相關屬性this.w = w this.h = h this.x = x this.y = y this.color = color this.Canvas = Canvas }}
下面運行一波試試
// 建立Canvas實例,並加入藍色個寬高100px,位置(100,100)、(300,100)紅色和藍色的色塊var canvas = new Canvas(document.getElementById('canvas')) canvas.createBlock({document.getElementById('canvas')) canvas.createBlock({ // 紅色x: 100, y: 100, w: 100, h: 100, color: '#f00' }) canvas.createBlock({ // 藍色x: 100, y: 100, w: 300, h: 100, color: '#00f' })
運行結果如下:
2.給色塊添加點擊事件這裡並不能直接給色塊添加點擊事件的,所以要用座標的方式判斷目前點擊的是哪個色塊。
class Block { // ...省略部分程式碼checkBoundary (x, y) { // 判斷邊界方法return x > this.x && x < (this.x + this.w) && y > this.y && y < (this.y + this.h) } mousedownEvent () { // 點選事件console.log(`點擊了顏色為${this.color}的色塊`) }}class Canvas { // ....省略部分程式碼constructor (ele) { this.canvas = ele this.ctx = this.canvas.getContext('2d') this.blockList = [] // 事件綁定(這裡有一個要注意的,我這裡用了bind方法,是為了將mousedownEvent方法內的this指向切換到Canvas) this.canvas.addEventListener('click', this.mousedownEvent.bind(this)) //點選事件} mousedownEvent () { // 點選事件const x = e.offsetX const y = e.offsetY // 這裡將點擊的座標傳給所有色塊,根據邊界判斷方法判斷是否在點擊在內部。是的話執行色塊的事件方法。 this.blockList.forEach(ele => { if (ele.checkBoundary(x, y)) ele.mousedownEvent(e) }) }}
到這裡為止已經實現了對不同canvas內不同色塊綁定對應的點擊事件。不過這個點擊事件是不完美的,因為目前為止我們還沒有引入層級的概念,就是說兩個色塊重疊部分點擊的話,全部都會觸發。所以我們還要給色塊加入層級的屬性。實現一個點擊某一個色塊改色塊的層級就會提升到最高。
class Block { // ...省略部分程式碼constructor ({ w, h, x, y, color, Canvas, hierarchy }) { // 初始化設定色塊相關屬性this.w = w this.h = h this. x = x this.y = y this.color = color this.Canvas = Canvas this.hierarchy = 0 }}class Canvas { // ...省略部分程式碼constructor (ele) { this.canvas = ele this.ctx = this.canvas.getContext('2d') this.blockList = [] // 事件綁定(這裡有一個要注意的,我這裡用了bind方法,是為了將mousedownEvent方法內的this指向切換到Canvas) this.canvas.addEventListener('click', this.mousedownEvent.bind(this)) // 點擊事件this.nowBlock = null //目前選取的色塊} createBlock (option) { // 建立色塊函數(這裡的Block是色塊的類別) option.Canvas = this // 建立最新的色塊的層級應該是最高的option.hierarchy = this .blockList.length this.blockList.push(new Block(option)) this.rendering() } mousedownEvent (e) { // 點選事件const x = e.offsetX const y = e.offsetY // 取得點中裡層級最高的色塊this.nowBlock = (this.blockList.filter(ele => ele.checkBoundary(x, y))).pop() // 如果沒有捕獲的色塊直接退出if (!this.nowBlock) return // 將點擊到的色塊層級提高到最高this.nowBlock.hierarchy = this.blockList.length // 重新排序(從小到大) this.blockList.sort((a, b) => a.hierarchy - b.hierarchy) // 在重新從0開始分配層級this.blockList.forEach( (ele, idx) => ele.hierarchy = idx) // 重新倒序排序後再重新渲染。 this.painting() this.nowBlock.mousedownEvent(e) // 只觸發選中的色塊的事件}}// 這裡我們還得加入第三塊色塊與紅色色塊重疊的色塊canvas.createBlock({ x: 150, y: 150, w: 100, h: 100, color: '#0f0'})
Canvas中mousedownEvent方法內的程式碼是有點複雜的,主要是有點繞。
運行後的效果就是下面這樣了:
3.實現對不同色塊進行拖曳在上面我們已經實作了取得不同的色塊,並修改它的層級。下面我們要實現色塊的拖曳,主要就是取得滑鼠移動過程中和一開始點擊下去時位置座標的變化。這個原理和普通的dom拖曳實現原理一樣。
取得點擊色塊的點,距離色塊左邊和上邊的距離(disX, disY)。
滑鼠移動時,用滑鼠目前距離canvas左邊和上邊的距離減去(disX, disY)這裡就是色塊的x,y座標了。
class Block { // ...省略部分程式碼mousedownEvent (e: MouseEvent) { /* 這裡disX與disY的計算方式: e.offsetX取得到的是滑鼠點選距離canvas左邊的距離,this.x是色塊距離canvas左邊的距離。 e.offsetX-this.x就是色塊左邊的距離。這應該很好理解了*/ const disX = e.offsetX - this.x // 點擊時距離色塊左邊的距離const disY = e.offsetY - this.y // 點擊時距離色塊上邊的距離//綁定滑鼠滑動事件;這裡mouseEvent.offsetX同樣是滑鼠距離canvas左側的距離,mouseEvent.offsetX - disX就是色塊的x座標了。同理y也是這樣算的。最後在重新渲染就好了。 document.onmousemove = (mouseEvent) => { this.x = mouseEvent.offsetX - disX this.y = mouseEvent.offsetY - disY this.Canvas.painting() } // 滑鼠鬆開則清除所有事件document.onmouseup = ( ) => { document.onmousemove = document.onmousedown = null } // console.log(`點擊了顏色為${this.color}的色塊22`) }}
效果如下:
下面貼上完整的程式碼(html和呼叫的方法就不放了)這個例子只是簡單實作給canvas內的內容綁定事件,大家可以實現複雜一點的,例如把色塊換成圖片,除了拖曳還以給圖片縮放,旋轉,刪除等等。
class Canvas { blockList: Block[] ctx: any canvas: any nowBlock: Block createBlock (option) { option.hierarchy = this.blockList.length option.Canvas = this this.blockList.push(new Block(option)) this. painting() } rendering (block) { this.ctx.fillStyle = block.color this.ctx.fillRect(block.x, block.y, block.w, block.h) } painting () { // 清空畫布this.ctx.fillStyle = '#fff' this.ctx.fillRect( 0, 0, this.canvas.width, this.canvas.height) this.blockList.forEach(ele => { this.rendering(ele) }) } mousedownEvent (e: MouseEvent) { // 點選事件const x = e.offsetX const y = e.offsetY // 取得點中里層級最高的色塊this.nowBlock = (this.blockList .filter(ele => ele.checkBoundary(x, y))).pop() // 如果沒有捕捉的色塊直接退出if (!this.nowBlock) return // 將點擊到的色塊層級提高到最高this.nowBlock.hierarchy = this.blockList.length // 重新排序(從小到大) this.blockList.sort((a, b) => a.hierarchy - b.hierarchy) // 在重新從0開始分配層級this.blockList.forEach((ele, idx) => ele.hierarchy = idx) //重新倒序排序後再重新渲染。 this.painting() this.nowBlock.mousedownEvent(e) // this.blockList.forEach(ele => { // if (ele.checkBoundary(x, y)) ele.clickEvent(e) // }) } constructor (ele) { this.canvas = ele this.ctx = this.canvas.getContext('2d') this.blockList = [] //事件綁定this.canvas.addEventListener('mousedown', this.mousedownEvent.bind(this)) }}class Block { w: number h: number x: number y: number color: string Canvas: Canvas hierarchy: number constructor ( { w, h, x, y, color, Canvas, hierarchy }) { this.w = w this.h = h this.x = x this.y = y this.color = color this.Canvas = Canvas this.hierarchy = hierarchy } checkBoundary (x, y) { return x > this.x && x < (this.x + this.w) && y > this.y && y < (this.y + this.h) } mousedownEvent (e: MouseEvent) { const disX = e.offsetX - this.x const disY = e.offsetY - this.y document.onmousemove = (mouseEvent) => { this.x = mouseEvent.offsetX - disX this.y = mouse.offsetY - EventY this.vasvas.painting.vasvas. () } document.onmouseup = () => { document.onmousemove = document.onmousedown = null } // console.log(`點擊了顏色為${this.color}的色塊22`) }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。