--- title: 'leaflet裡建立canvas' disqus: hackmd --- leaflet裡建立canvas === ![downloads](https://img.shields.io/github/downloads/atom/atom/total.svg) ![build](https://img.shields.io/appveyor/ci/:user/:repo.svg) ![chat](https://img.shields.io/discord/:serverId.svg) 本篇使用JS語法 <https://leafletjs.com/> leaflet官網 <https://www.w3schools.com/tags/ref_canvas.asp> 一些canvas的屬性 ## Table of Contents [TOC] ## 目的 本來的leaflet有自己的方式建立colorbar, 但要做出來的colorbar要計算色階且文字跟色階個數不一樣,後來採用canvas來畫。歡迎大家再提供更好的方式!!!! ## First - 產地圖 首先使用leaflet.js產生地圖,並定位於臺灣 > leaflet ```gherkin= this.map = L.map('map').setView([23.473875, 120.982024], 8); this.tileLayer = L.tileLayer("", //'http://{s}.tile.osm.org/{z}/{x}/{y}.png',//中文地圖 { maxZoom: 8, minZoom: 0, bounds:[ [19.715015145512087, 117.49902343749999], [26.892679095908164, 123.969482421875] ], attribution: '' // attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }); ``` ## Second - 建立canvas並弄上leaflet ```gherkin= let legend = L.control({position: 'bottomleft'}); legend.onAdd = function (map) { let canvas = L.DomUtil.create('canvas', 'custom_class'); var ctx = canvas.getContext('2d'); // to do... // 下面二行只是先簡單弄個文字 ctx.font = "12px Arial"; ctx.fillText("Hello World", 10, 50); return canvas; }.bind(this); legend.addTo(this.map); ``` > 在上面程式有設定一個class(custom_class), style裡面可以自訂 > 其實這樣就可以簡單的建立canvas囉!!!!收工。但事情不是這麼簡單的,我還要畫個colorbar跟文字,嗚嗚 ## Third - canvas畫出colorbar 在上面to do的地方下面,我要建立colorbar喔 ```gherkin= for(var i = 0; i <= 255; i++) { ctx.beginPath(); var color = 'rgb(100, ' + i + ', ' + i + ')'; ctx.fillStyle = color; ctx.fillRect(0, i * 2, 10, 2); } ``` > 這兒就可以建立簡易的colorbar囉! ## Appendix and FAQ :::info **Find this document incomplete?** Leave a comment! ::: ###### tags: `leaflet` `canvas`