溫馨提示×

溫馨提示×

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

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

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

發(fā)布時(shí)間:2022-02-21 09:59:39 來源:億速云 閱讀:193 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“html5中如何使用canvas標(biāo)簽畫出平滑的曲線”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“html5中如何使用canvas標(biāo)簽畫出平滑的曲線”吧!

背景概要

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

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

<!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)邏輯也很簡單:

  • 我們在canvas畫布上主要監(jiān)聽了三個(gè)事件:mousedown、mouseupmousemove,同時(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)基本的畫板功能了,然而事情并沒那么簡單,仔細(xì)的童鞋也許會(huì)發(fā)現(xiàn)一個(gè)很嚴(yán)重的問題——通過這種方式畫出來的線條存在鋸齒,不夠平滑,而且你畫得越快,折線感越強(qiáng)。表現(xiàn)如下圖所示:

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

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

問題分析

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

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

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

受限于瀏覽器對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):

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

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

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

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

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

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

假設(shè)我們在一次繪畫中共采集到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繪制一條二次貝塞爾曲線線段;

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

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

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

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

html5中如何使用canvas標(biāo)簽畫出平滑的曲線

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

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í)才開始繪制。接下來的處理就跟該算法一毛一樣了,這里不再贅述。

到此,相信大家對“html5中如何使用canvas標(biāo)簽畫出平滑的曲線”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

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

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

AI