這篇文章主要介紹了canvas在繪圖時(shí)位置偏離怎么辦,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
成都創(chuàng)新互聯(lián)公司專注于企業(yè)全網(wǎng)整合營銷推廣、網(wǎng)站重做改版、姜堰網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5網(wǎng)站設(shè)計(jì)、購物商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為姜堰等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
使用 canvas 繪圖時(shí),指定的 div 大小一定不要超過該 div 所能獲得的最大范圍,否則繪制的點(diǎn)會(huì)跟實(shí)際位置發(fā)生偏離。
例如
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled 1</title> <style type="text/css"> .style1 { font-size: x-small; } </style> </head> <body > <div style="margin:2%"> <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9"> <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas> </div> </div> <script type="text/javascript"> var paint = false; var start = false; var canvas = document.getElementById("container"); canvas.width = 800; canvas.height = 800; var offsetY = canvas.offsetTop; var offsetX = canvas.offsetLeft; var y; var x; var context = canvas.getContext("2d"); function mousemove(e) { if (paint == true){ if (start == false){ context.moveTo(0, 0); start = true; } else { context.moveTo(x, y); } x = e.pageX - offsetX; y = e.pageY - offsetY; context.lineTo(x, y); context.stroke(); } } function mousedown(event) { paint = true; console.log("down") } function mouseup(event) { paint = false; console.log("up") } </script> </body> </html>
上例中可以正確的繪制線圖。
如果更改為:
<div style="margin:20%"> <div id="test" style="width:800px;height:800px;background-color:#cbdad0d9"> <canvas id="container" onmousemove="mousemove(event)" onmousedown="mousedown()" onmouseup="mouseup()"></canvas> </div> </div>
由于 canvas 所需 width 800px 無法滿足,因此繪制線圖時(shí),與實(shí)際鼠標(biāo)位置發(fā)生偏離。
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“canvas在繪圖時(shí)位置偏離怎么辦”這篇文章對大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
網(wǎng)站欄目:canvas在繪圖時(shí)位置偏離怎么辦
網(wǎng)頁網(wǎng)址:http://bm7419.com/article46/jdeoeg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、品牌網(wǎng)站建設(shè)、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站建設(shè)、ChatGPT、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)