主頁 > 知識(shí)庫 > canvas 繪圖時(shí)位置偏離的問題解決

canvas 繪圖時(shí)位置偏離的問題解決

熱門標(biāo)簽:美圖手機(jī) 智能手機(jī) 檢查注冊(cè)表項(xiàng) 網(wǎng)站建設(shè) 使用U盤裝系統(tǒng) 硅谷的囚徒呼叫中心 阿里云 百度競價(jià)點(diǎn)擊價(jià)格的計(jì)算公式

使用 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ā)生偏離。

到此這篇關(guān)于canvas 繪圖時(shí)位置偏離的問題解決的文章就介紹到這了,更多相關(guān)canvas 繪圖位置偏離內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!

標(biāo)簽:賀州 山南 黃山 湘潭 通遼 湖北 煙臺(tái) 懷化

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《canvas 繪圖時(shí)位置偏離的問題解決》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266