Canvas作圖

来源:https://www.cnblogs.com/donghuang/archive/2018/02/10/8437954.html
-Advertisement-
Play Games

什麼是 Canvas?   canvas 元素用於在網頁上繪製圖形。 ...


  前幾天項目GIS部分一個功能模塊需要一個控制儀錶盤,雖然之前看過canvas作圖,但是沒怎麼具體用過。今天就這個功能模塊研究了下canvas。

什麼是 Canvas?

  canvas 元素用於在網頁上繪製圖形。<canvas> 元素本身並沒有繪製能力(它僅僅是圖形的容器),必須使用腳本來完成實際的繪圖任務,通常是用JavaScript在網頁上繪製圖像。canvas所在畫布是一個矩形區域,我們可以控制畫布的每一像素。canvas 擁有多種繪製路徑、矩形、圓形、字元以及添加圖像的方法。一句話說完,功能很強大,需要研究的東西很多!

創建 Canvas 元素

  在 HTML5 頁面添加 canvas 元素。規定元素的 id、和寬高:

<body>
  <canvas id="canvas" width="400" height="400"></canvas>
</body>

  Canvas 對象表示一個 HTML 畫布元素 - <canvas>。它沒有自己的行為,但是定義了一個 很多API 支持腳本化客戶端繪圖操作。

Canvas 對象的屬性

  height 屬性

    畫布的高度。和一幅圖像一樣,這個屬性可以指定為一個整數像素值或者是視窗高度的百分比。當這個值改變的時候,在該畫布上已經完成的任何繪圖都會擦除掉。預設值是 300。

  width 屬性

    畫布的寬度。和一幅圖像一樣,這個屬性可以指定為一個整數像素值或者是視窗寬度的百分比。當這個值改變的時候,在該畫布上已經完成的任何繪圖都會擦除掉。預設值是 300。

 

具體的實驗代碼如下,效果可直接執行代碼測試:所有的註釋都寫在了代碼裡面,故不另行做註釋

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <style type="text/css">
        canvas {
            border: 1px solid red;
            background-color: #fff;
            cursor: pointer;
        }

        input {
            position: absolute;
            font-size: 20px;
            color: #f8b500;
            top: 18%;
            left: 9%;
            width: 100px;
            height: 30px;
            line-height: 28px;
            text-align: center;
        }
    </style>
</head>
<body>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<input id="canvasText" value="">
<script>
    var canvasDrawing = {
        /**繪圖對象初始化
         * 參數:type 初始化類型。arc:圓弧形;bar :柱狀圖
         */
        init: function (type) {
            this.canvas = document.getElementById("canvas");    //獲取用於canvas作圖的對象
            this.canvasEnv = this.canvas.getContext("2d");    //getContext()返回一個用於在畫布上繪圖的環境。當前唯一的合法參數值是 "2d",它指定了二維繪圖。
            this.pathr = 120;  //滑動路徑半徑
            if(type === "arc"){
                this.event();       //事件綁定初始化
                this.canvasDrawing.prototype = this; //canvasDrawing方法繼承父元素內方法
                this.ex = new this.canvasDrawing(type, 200, 200, 120);  //初始化創建實例,預設畫弧形圖
            }else {
                this.arr=[60, 90, 150, 130, 170, 190, 125, 175, 155, 165, 155, 145];
                this.ex = new this.canvasDrawing(type, 70, 280, 330, 280);  //初始化創建實例,根據type類型canvas作圖;此處為柱狀圖
            }
        },
        /**事件綁定
         */
        event: function () {
            this.canvas.addEventListener("mousedown", this.onMouseDown.bind(this), false);
            this.canvas.addEventListener("mousemove", this.onMouseMove.bind(this), false);
            this.canvas.addEventListener("mouseup", this.onMouseUp.bind(this), false);
        },
        /**繪製圖形
         * 參數:type繪圖類型;x,y圓心位置;r內圓弧半徑;j可變圓弧結束位置,bgc圓弧顏色
         */
        canvasDrawing: function (type, x, y, r, j, bgc) {
            if (type === "arc") {
                this.canvasEnv.clearRect(0, 0, 400, 400);
                this.x = x;
                this.y = y;
                this.r = r;
                this.j = j || 0.85 * Math.PI;

                this.canvasEnv.beginPath();
                this.canvasEnv.lineWidth = 3;
                this.canvasEnv.arc(this.x, this.y, this.r + 15, Math.PI * 0.85, Math.PI * 0.15, false); // 繪製外層單弧線
                this.canvasEnv.strokeStyle = '#f8b500';
                this.canvasEnv.stroke();

                this.canvasEnv.beginPath();
                this.canvasEnv.arc(this.x, this.y, this.r, Math.PI * 0.85, this.j, false); // 可變條狀圓弧
                this.innerText = ((((this.j / Math.PI) - 0.85) * 100) / 1.3).toFixed(0);
                this.innerText = (this.innerText === "-0") ? (0) : (this.innerText);
                document.getElementById("canvasText").value = this.innerText;
                this.canvasEnv.strokeStyle = (bgc == undefined) ? (this.colorChoose(this.innerText)) : (bgc);
                this.canvasEnv.lineCap = "butt";
                this.canvasEnv.lineWidth = 20;
                this.canvasEnv.stroke();
            } else {        //繪製柱狀圖
                this.sX = x;
                this.sY = y;
                this.eX = r;
                this.eY = j;
                this.canvasEnv.beginPath();
                this.canvasEnv.moveTo(this.sX, this.sY);
                this.canvasEnv.lineTo(this.eX, this.eY);
                this.canvasEnv.stroke();
                for (var i = 0; i < 12; i++) {
                    var width = 10;
                    var height = this.arr[i];
                    var X = 85 + i * 20;
                    var Y = 280 - height;
                    this.canvasEnv.beginPath();
                    this.canvasEnv.fillStyle = "#900b09";
                    this.canvasEnv.rect(X, Y, width, height);   //rect():創建矩形
                    this.canvasEnv.fill();
                    this.canvasEnv.closePath()
                }
            }
        },
        /**確定按下滑鼠位置
         */
        onMouseDown: function (event) {
            var X = this.getX(event);   //獲取滑鼠左鍵按下所在的X坐標
            var Y = this.getY(event);   //獲取滑鼠左鍵按下所在的Y坐標
            var minX = this.ex.x - 2 * this.ex.r, msXX = this.ex.x + 2 * this.ex.r;     //滑鼠按下橫向區間
            var minY = this.ex.y - 2 * this.ex.r, msXY = this.ex.y + 2 * this.ex.r;     //滑鼠按下縱向區間
            if ((minX < X && X < msXX) && (minY < Y && Y < msXY)) {   //判斷滑鼠是否在可允許區間
                this.ex.isDown = true;
            } else {
                this.ex.isDown = false;
            }
        },
        /**滑鼠釋放
         */
        onMouseUp: function () {
            this.ex.isDown = false
        },
        /**滑鼠移動
         */
        onMouseMove: function (event) {
            if (this.ex.isDown) {
                var coordinate = {
                    "x": this.getX(event),
                    "y": this.getY(event)
                };
                var quadrantDoordinate = this.coordTransform(coordinate);
                if (this.check(quadrantDoordinate.x, quadrantDoordinate.y)) {
                    var co = this.getMoveto(quadrantDoordinate.x, quadrantDoordinate.y);
                    if (co == null) return;
                    this.ex.canvasDrawing("arc", this.ex.x, this.ex.y, this.ex.r, co.z);
                }
            }
        },
        /**canvas內坐標轉換為圓形圖內坐標
         */
        coordTransform: function (coordinates) {
            var target = new Object();      //象限按照數學順時針劃分
            if (coordinates.x > this.ex.x && coordinates.y > this.ex.y) {           //第一象限
                target.x = -(this.ex.x - coordinates.x);
                target.y = this.ex.y - coordinates.y;
            } else if (coordinates.x > this.ex.x && coordinates.y < this.ex.y) {      //第二象限
                target.x = -(this.ex.x - coordinates.x);
                target.y = this.ex.y - coordinates.y;
            } else if (coordinates.x < this.ex.x && coordinates.y < this.ex.y) {       //第三象限
                target.x = -(this.ex.x - coordinates.x);
                target.y = this.ex.y - coordinates.y;
            } else if (coordinates.x < this.ex.x && coordinates.y > this.ex.y) {       //第四象限
                target.x = -(this.ex.x - coordinates.x);
                target.y = this.ex.y - coordinates.y;
            }
            return target;
        },
        /**限制滑鼠可拖動範圍
         */
        check: function (x, y) {
            var xx = x * x;
            var yy = y * y;
            var minArea = (this.ex.x - this.ex.r) * (this.ex.x - this.ex.r);    //可滑動最小區域
            var msXArea = (this.ex.x - this.ex.r / 4) * (this.ex.x - this.ex.r / 4);  //可滑動最大區域
            if (xx + yy > minArea && xx + yy < msXArea) {
                return true;
            } else {
                return false;
            }
        },
        getMoveto: function (x, y) {
            if (!this.ex.isDown) {
                return null;
            }
            var temp = new Object();
            temp.o = Math.atan(y / x); //滑鼠移動點圓形角
            temp.x = this.pathr * Math.cos(temp.o);
            temp.y = this.pathr * Math.sin(temp.o);
            if (y < -60) { //坐標點處理;這裡判斷沒處理好,坐標判定有些問題,滑鼠滑動到-60上下,容易將最下麵一段圓弧也畫出來
                return null;
            }
            if (x > 0) {  //弧度值計算
                temp.z = -Math.atan(temp.y / temp.x) + Math.PI * 2;
            } else {
                temp.z = -Math.atan(temp.y / temp.x) + Math.PI;
            }
            if (temp.z > 6.77) {  //條狀圓弧最大值(右下角位置)
                temp.z = 6.77;
                temp.x = this.pathr * Math.cos(Math.PI * 2.05);
                temp.y = -this.pathr * Math.sin(Math.PI * 2.05);
            } else if (temp.z < 2.67) { //條狀圓弧最小值(左下角位置)
                temp.z = 2.67;
                temp.x = -this.pathr * Math.cos(Math.PI * 0.85);
                temp.y = -this.pathr * Math.sin(Math.PI * 0.85);
            }
            return temp;
        },
        /**獲取滑鼠在canvas內坐標x
         */
        getX: function (event) {
            return event.clientX - this.canvas.getBoundingClientRect().left;
        },
        /**獲取滑鼠在canvas內坐標y
         */
        getY: function (event) {
            return event.clientY - this.canvas.getBoundingClientRect().top;
        },
        /**根據數值進行顏色的變換
         */
        colorChoose: function (val) {
            var color = null;
            var marginLeftSet = document.getElementById("canvasText");
            if (val > 90) {
                color = "#FFD800";
            } else if (val > 75) {
                color = "#BF9900";
            } else if (val > 60) {
                color = "#997C00";
            } else if (val > 45) {
                color = "#725B00";
            } else if (val > 30) {
                color = "#4C3B00";
            } else if (val > 15) {
                color = "#261D00";
            } else {
                color = "#000000";
            }
            if (val == 100) {
                marginLeftSet.style.marginLeft = "-10px";
            } else if (val < 10) {
                marginLeftSet.style.marginLeft = "-30px";
            } else {
                marginLeftSet.style.marginLeft = "-20px";
            }
            return color;
        }
    };
    canvasDrawing.init("arc");
    /**給文本框綁定事件;同時回車更改圓弧形狀
     */
    document.getElementById("canvasText").addEventListener("keydown", function (event) {
        var keyCode = window.event ? event.keyCode : event.which;
        var value = document.getElementById("canvasText").value;
        if (keyCode == 13 && (value != undefined && value != null)) {
            if (parseInt(value) <= 0) {
                value = 0;
            } else if (parseInt(value) >= 100) {
                value = 100;
            }
            canvasDrawing.canvasDrawing("arc", 200, 200, 120, ((1.3 * parseInt(value)) / 100 + 0.85) * Math.PI, canvasDrawing.colorChoose(value));
        }
    }, false);
</script>
</body>
</html>

效果圖如下:(中間顯示值表示當前弧形占比。值為0~100)


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、核心動畫概念 -導入QuartzCore.framework框架 1⃣ 開發步驟1.初始化一個動畫對象(CAAnimation)並且設置一些動畫相關屬性 2.CALayer中很多屬性都可以通過CAAnimation實現動畫效果,包括:opacity、position、transform、boun ...
  • 翻轉的動畫 旋轉動畫 偏移動畫 翻頁動畫 縮放動畫 取反的動畫效果是根據當前的動畫取他的相反的動畫 ...
  • 前言 剛接手電筒子書項目時,和安卓開發者pt Cai老師【aipiti Cai,一個我很敬佩很資深的開發工程師,設計領域:c++、Java、安卓、QT等】共同商議了一下,因為項目要做要同步,移動端【手機端】和PC【電腦端】的同步問題,讓我們無法決定該用那種方式去呈現電子書,因為PC要展示的電子書有網路 ...
  • 介紹 Runloop是一種事件監聽迴圈,可以理解成一個while死迴圈,監聽到事件就起來,沒有就休息。 Runloop可以在不同模式下進行切換,iOS有五種模式,其中UIInitializationRunLoopModel應用程式啟動時會使用,啟動完成後將不再使用;GSEventReceiveRun ...
  • 首先這應該是一個老生常談的設計了,但是畢竟身為小白的自己都沒動手做過,不動手怎麼提高自己呢,所以在這梅林沉船閑暇之際,我就把我的設計流程與思路記錄下來。首先來看看效果圖吧: 如上圖就是一個簡單並沒有美化過的時鐘,接下來我就來講講我的設計流程與思路。 一.首先繼承view重寫裡面的onDraw方法。 ...
  • 閱讀目錄 一、什麼是記憶體泄露? 二、記憶體泄露的危害 三、解決方案 四、總結 一、什麼是記憶體泄露? Java使用有向圖機制,通過GC自動檢查記憶體中的對象(什麼時候檢查由虛擬機決定),如果GC發現一個或一組對象為不可到達狀態,則將該對象從記憶體中回收。也就是說,一個對象不被任何引用所指向,則該對象會在被G ...
  • Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated whe ...
  • 本地/推送通知為不同的需要而設計。本地通知對於iPhone,iPad或iPod來說是本地的。而推送通知——來自於設備外部。它們來自遠程伺服器——也叫做遠程通知——推送給設備上的應用程式(使用APNs)同時可以查看消息或下載數據。 APNS: 蘋果推送通知服務 “Apple Push Notifica ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...