App下載

html5怎么使用canvas標(biāo)簽畫出平滑的曲線?canvas曲線畫法案例分享!

猿友 2021-07-17 13:49:11 瀏覽數(shù) (3003)
反饋

相信不同學(xué)在數(shù)學(xué)課中有被老師要求畫一個(gè)折線圖、線性圖和曲線圖等等之類的圖,那么今天我們就來和大家聊聊:“html5怎么使用canvas標(biāo)簽畫出平滑的曲線?”這個(gè)問題。下面是相關(guān)的內(nèi)容大家可以做為參考資料!

背景概要

相信大家平時(shí)在學(xué)習(xí)canvas 或 項(xiàng)目開發(fā)中使用canvas的時(shí)候應(yīng)該都遇到過這樣的需求:實(shí)現(xiàn)一個(gè)可以書寫的畫板小工具。

嗯,相信這對(duì)canvas使用較熟的童鞋來說僅僅只是幾十行代碼就可以搞掂的事情,以下demo就是一個(gè)再也簡(jiǎn)單不過的例子了:

<!DOCTYPE html>
<html>
<head>
    <title>Sketchpad demo</title>
    <style type="text/css">
        canvas {
            border: 1px blue solid; 
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="800" height="500"></canvas>
    <script type="text/javascript">
        let isDown = false;
        let beginPoint = null;
        const canvas = document.querySelector('#canvas');
        const ctx = canvas.getContext('2d');

        // 設(shè)置線條顏色
        ctx.strokeStyle = 'red';
        ctx.lineWidth = 1;
        ctx.lineJoin = 'round';
        ctx.lineCap = 'round';

        canvas.addEventListener('mousedown', down, false);
        canvas.addEventListener('mousemove', move, false);
        canvas.addEventListener('mouseup', up, false);
        canvas.addEventListener('mouseout', up, false);

        function down(evt) {
            isDown = true;
            beginPoint = getPos(evt);
        }

        function move(evt) {
            if (!isDown) return;
            const endPoint = getPos(evt);
            drawLine(beginPoint, endPoint);
            beginPoint = endPoint;
        }

        function up(evt) {
            if (!isDown) return;
            
            const endPoint = getPos(evt);
            drawLine(beginPoint, endPoint);

            beginPoint = null;
            isDown = false;
        }

        function getPos(evt) {
            return {
                x: evt.clientX,
                y: evt.clientY
            }
        }

        function drawLine(beginPoint, endPoint) {
            ctx.beginPath();
            ctx.moveTo(beginPoint.x, beginPoint.y);
            ctx.lineTo(endPoint.x, endPoint.y);
            ctx.stroke();
            ctx.closePath();
        }
    </script>
</body>
</html>

它的實(shí)現(xiàn)邏輯也很簡(jiǎn)單:

  • 我們?cè)赾anvas畫布上主要監(jiān)聽了三個(gè)事件:mousedownmouseupmousemove,同時(shí)我們也創(chuàng)建了一個(gè)isDown變量;
  • 當(dāng)用戶按下鼠標(biāo)(mousedown,即起筆)時(shí)將isDown置為true,而放下鼠標(biāo)(mouseup)的時(shí)候?qū)⑺脼?code>false,這樣做的好處就是可以判斷用戶當(dāng)前是否處于繪畫狀態(tài);
  • 通過mousemove事件不斷采集鼠標(biāo)經(jīng)過的坐標(biāo)點(diǎn),當(dāng)且僅當(dāng)isDowntrue(即處于書寫狀態(tài))時(shí)將當(dāng)前的點(diǎn)通過canvas的lineTo方法與前面的點(diǎn)進(jìn)行連接、繪制;

通過以上幾個(gè)步驟我們就可以實(shí)現(xiàn)基本的畫板功能了,然而事情并沒那么簡(jiǎn)單,仔細(xì)的童鞋也許會(huì)發(fā)現(xiàn)一個(gè)很嚴(yán)重的問題——通過這種方式畫出來的線條存在鋸齒,不夠平滑,而且你畫得越快,折線感越強(qiáng)。表現(xiàn)如下圖所示:

為什么會(huì)這樣呢?

問題分析

出現(xiàn)該現(xiàn)象的原因主要是:

我們是以canvas的lineTo方法連接點(diǎn)的,連接相鄰兩點(diǎn)的是條直線,非曲線,因此通過這種方式繪制出來的是條折線;

受限于瀏覽器對(duì)mousemove事件的采集頻率,大家都知道在mousemove時(shí),瀏覽器是每隔一小段時(shí)間去采集當(dāng)前鼠標(biāo)的坐標(biāo)的,因此鼠標(biāo)移動(dòng)的越快,采集的兩個(gè)臨近點(diǎn)的距離就越遠(yuǎn),故“折線感越明顯“;

如何才能畫出平滑的曲線?

要畫出平滑的曲線,其實(shí)也是有方法的,lineTo靠不住那我們可以采用canvas的另一個(gè)繪圖API——quadraticCurveTo ,它用于繪制二次貝塞爾曲線。

二次貝塞爾曲線

quadraticCurveTo(cp1x, cp1y, x, y)

調(diào)用quadraticCurveTo方法需要四個(gè)參數(shù),cp1x、cp1y描述的是控制點(diǎn),而x、y則是曲線的終點(diǎn):

更多詳細(xì)的信息可移步MDN

既然要使用貝塞爾曲線,很顯然我們的數(shù)據(jù)是不夠用的,要完整描述一個(gè)二次貝塞爾曲線,我們需要:起始點(diǎn)、控制點(diǎn)和終點(diǎn),這些數(shù)據(jù)怎么來呢?

有一個(gè)很巧妙的算法可以幫助我們獲取這些信息

獲取二次貝塞爾關(guān)鍵點(diǎn)的算法

這個(gè)算法并不難理解,這里我直接舉例子吧:

假設(shè)我們?cè)谝淮卫L畫中共采集到6個(gè)鼠標(biāo)坐標(biāo),分別是A, B, C, D, E, F;取前面的A, B, C三點(diǎn),計(jì)算出BC的中點(diǎn)B1,以A為起點(diǎn),B為控制點(diǎn),B1為終點(diǎn),利用quadraticCurveTo繪制一條二次貝塞爾曲線線段;

接下來,計(jì)算得出CD點(diǎn)的中點(diǎn)C1,以B1為起點(diǎn)、C為控制點(diǎn)、C1為終點(diǎn)繼續(xù)繪制曲線;

依次類推不斷繪制下去,當(dāng)?shù)阶詈笠粋€(gè)點(diǎn)F時(shí),則以DE的中點(diǎn)D1為起點(diǎn),以E為控制點(diǎn),F為終點(diǎn)結(jié)束貝塞爾曲線。

OK,算法就是這樣,那我們基于該算法再對(duì)現(xiàn)有代碼進(jìn)行一次升級(jí)改造:

let isDown = false;
let points = [];
let beginPoint = null;
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

// 設(shè)置線條顏色
ctx.strokeStyle = 'red';
ctx.lineWidth = 1;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';

canvas.addEventListener('mousedown', down, false);
canvas.addEventListener('mousemove', move, false);
canvas.addEventListener('mouseup', up, false);
canvas.addEventListener('mouseout', up, false);

function down(evt) {
    isDown = true;
    const { x, y } = getPos(evt);
    points.push({x, y});
    beginPoint = {x, y};
}

function move(evt) {
    if (!isDown) return;

    const { x, y } = getPos(evt);
    points.push({x, y});

    if (points.length > 3) {
        const lastTwoPoints = points.slice(-2);
        const controlPoint = lastTwoPoints[0];
        const endPoint = {
            x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
            y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
        }
        drawLine(beginPoint, controlPoint, endPoint);
        beginPoint = endPoint;
    }
}

function up(evt) {
    if (!isDown) return;
    const { x, y } = getPos(evt);
    points.push({x, y});

    if (points.length > 3) {
        const lastTwoPoints = points.slice(-2);
        const controlPoint = lastTwoPoints[0];
        const endPoint = lastTwoPoints[1];
        drawLine(beginPoint, controlPoint, endPoint);
    }
    beginPoint = null;
    isDown = false;
    points = [];
}

function getPos(evt) {
    return {
        x: evt.clientX,
        y: evt.clientY
    }
}

function drawLine(beginPoint, controlPoint, endPoint) {
    ctx.beginPath();
    ctx.moveTo(beginPoint.x, beginPoint.y);
    ctx.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
    ctx.stroke();
    ctx.closePath();
}

在原有的基礎(chǔ)上,我們創(chuàng)建了一個(gè)變量points用于保存之前mousemove事件中鼠標(biāo)經(jīng)過的點(diǎn),根據(jù)該算法可知要繪制二次貝塞爾曲線起碼需要3個(gè)點(diǎn)以上,因此我們只有在points中的點(diǎn)數(shù)大于3時(shí)才開始繪制。接下來的處理就跟該算法一毛一樣了,這里不再贅述。

代碼更新后我們的曲線也變得平滑了許多,如下圖所示:

那么以上就是今天和大家分享的有關(guān)于:“html5怎么使用canvas標(biāo)簽畫出平滑的曲線?”這個(gè)問題的相關(guān)內(nèi)容,當(dāng)然更多有關(guān)于html5這方面的內(nèi)容我們都可以在W3Cschool中進(jìn)行一個(gè)系統(tǒng)的學(xué)習(xí)和了解。


0 人點(diǎn)贊