Styling feature 与 CanvasGradient or CanvasPattern
Styling feature 与 CanvasGradient or CanvasPattern示例。 canvas gradient pattern 样式
本示例创建了一个 CanvasGradient。矢量数据从文件中加载,要素使用该渐变进行填充。同样的技术也可以用于 CanvasPattern。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import KML from 'ol/format/KML.js';
import {DEVICE_PIXEL_RATIO} from 'ol/has.js';
import VectorLayer from 'ol/layer/Vector.js';
import {fromLonLat} from 'ol/proj.js';
import VectorSource from 'ol/source/Vector.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Style from 'ol/style/Style.js';
// 渐变和图案位于画布像素空间中,因此我们要根据渲染器的
// 像素比进行调整
const pixelRatio = DEVICE_PIXEL_RATIO;
// 生成一个彩虹渐变
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 1024 * pixelRatio, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1 / 6, 'orange');
gradient.addColorStop(2 / 6, 'yellow');
gradient.addColorStop(3 / 6, 'green');
gradient.addColorStop(4 / 6, 'aqua');
gradient.addColorStop(5 / 6, 'blue');
gradient.addColorStop(1, 'purple');
const vectorLayer = new VectorLayer({
background: 'white',
source: new VectorSource({
url: 'data/kml/states.kml',
format: new KML({extractStyles: false}),
}),
style: new Style({
fill: new Fill({color: gradient}),
stroke: new Stroke({
color: '#333',
width: 1,
}),
}),
});
const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: fromLonLat([-100, 38.5]),
zoom: 4,
}),
});index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用 CanvasGradient 或 CanvasPattern 设置要素样式</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "canvas-gradient-pattern",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}