起因:在cavnas繪制矩形時(shí) 鼠標(biāo)移動(dòng)一直在監(jiān)測(cè)中,所以鼠標(biāo)移動(dòng)的軌跡會(huì)留下一個(gè)個(gè)的矩形框,
要想清除矩形框官方給出了ctx.clearRect() 但是這樣是把整個(gè)畫布給清空了,因此需要不斷
向畫布展示新的圖片,這樣就出現(xiàn)了不斷閃屏的問題。
那么怎么解決呢?
microsoft提供了雙緩沖圖形技術(shù),可以點(diǎn)擊看看這邊文章。
具體就是畫圖的時(shí)候做兩個(gè)canvas層,一個(gè)臨時(shí)層 一個(gè)顯示層,鼠標(biāo)的監(jiān)聽事件放在顯示層處理,
每次清空的時(shí)候只清空臨時(shí)層,這樣就可以解決閃屏問題了。
部分代碼如下:
<!--臨時(shí)層--><canvas id="customPositionImg2" ref="table2" style=" display:none;"></canvas><!--顯示層 增加鼠標(biāo)按下,移動(dòng),松開事件--><canvas id="customPositionImg" ref="table" @mousedown="mousedown" @mousemove="mousemove" @mouseup="mouseup" style=""></canvas>
顯示層展示圖片:
//因?yàn)轫?xiàng)目是dialog展示自定義畫板,所以圖片展示就寫在了dialog打開的鉤子里,如果需要直接復(fù)制vue.nextTick里面的代碼就行show () { vue.nextTick(_ => { let customCanvas =this.$refs.table;// canvas顯示層 this.customstyle =''; customCanvas.height = 740; customCanvas.width = 1460; this.customcxt = customCanvas.getContext("2d"); let img = new Image(); img.src = this.imgSrc; let that = this; img.onload = function () { that.customRwidth = customCanvas.width / img.width; //原圖與展示圖片的寬高比 that.customRheight = customCanvas.height / img.height; that.customcxt.drawImage(img, 0, 0, customCanvas.width, customCanvas.height); }; })},鼠標(biāo)操作事件
//鼠標(biāo)按下時(shí)執(zhí)行mousedown(e){ this.isMouseDownInCanvas = true; // 鼠標(biāo)按下時(shí)開始位置與結(jié)束位置相同 防止鼠標(biāo)在畫完矩形后 點(diǎn)擊圖畫形成第二個(gè)圖形 this.endX = e.offsetX; this.endY = e.offsetY; this.startX = e.offsetX; this.startY = e.offsetY;},//鼠標(biāo)移動(dòng)式時(shí)執(zhí)行mousemove(e){ if (this.isMouseDownInCanvas){ // 當(dāng)鼠標(biāo)有按下操作時(shí)執(zhí)行 console.log( e.offsetX,e.offsetY); if((this.endX != e.offsetX)||( this.endY != e.offsetY)){ this.endX = e.offsetX; this.endY = e.offsetY; let wwidth = this.endX - this.startX; let wheigth = this.endY - this.startY; let tempCanvas = this.$refs.table2; // canvas臨時(shí)層 let tempCtx = tempCanvas.getContext('2d'); tempCanvas.width = 1460; tempCanvas.height = 740; // 設(shè)置寬高 // 清除臨時(shí)層指定區(qū)域的所有像素 tempCtx.clearRect(0, 0, 1460, 740); // 重新展示圖片 let img = new Image(); img.src = this.imgSrc; let that = this; img.onload = function () { that.customcxt.drawImage(img, 0, 0,1460, 740); }; this.customcxt.strokeStyle=" #00ff00"; //矩形框顏色 this.customcxt.lineWidth="2"; //矩形框?qū)挾? this.customcxt.strokeRect(this.startX,this.startY,wwidth,wheigth); //繪制矩形 }else{ //鼠標(biāo)按下靜止時(shí)顯示矩形的大小。 let wwidth2 = this.endX - this.startX; let wheigth2 = this.endY - this.startY; this.customcxt.strokeRect(this.startX,this.startY,wwidth2,wheigth2) } }},//鼠標(biāo)松開時(shí)執(zhí)行mouseup(e){ this.isMouseDownInCanvas = false; // 繪制最終的矩形框 let wwidth = this.endX - this.startX; let wheigth = this.endY - this.startY; this.customcxt.strokeRect(this.startX,this.startY,wwidth,wheigth)},
新聞熱點(diǎn)
疑難解答
圖片精選