溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

canvas在繪圖時(shí)位置偏離怎么辦

發(fā)布時(shí)間:2021-05-08 09:38:39 來(lái)源:億速云 閱讀:386 作者:小新 欄目:web開(kāi)發(fā)

這篇文章主要介紹了canvas在繪圖時(shí)位置偏離怎么辦,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

使用 canvas 繪圖時(shí),指定的 div 大小一定不要超過(guò)該 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 無(wú)法滿足,因此繪制線圖時(shí),與實(shí)際鼠標(biāo)位置發(fā)生偏離。

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“canvas在繪圖時(shí)位置偏離怎么辦”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI