OL3 OSM canvas
HTML
<script src="http://openlayers.org/en/v3.0.0/build/ol.js"></script>
<body onload="Initialize();">
<p><b>Canvas With OpenLayers & HTML5 Canvas Demo</b>
</p>
<div>
<div id="map" class="map" style="width:400px;height:600px;border:1px solid black;"></div>
<!-- div id="map" class="map"></div> -->
<div id="mapcanvas" style="width:400px;height:600px;border:1px solid black;" class="mapcanvas">
<canvas id="myCanvas">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
</div>
</body>
CSS
body {
font-family: sans-serif;
}
p {
width: 95%;
}
a {
text-decoration: none;
color: black;
font-weight: bold;
font-size: 1.1em;
}
div.map {
width: 45%;
height:90%;
float: left;
border-style:solid;
border-right-width:5%;
}
div.mapcanvas {
width: 45%;
height:90%;
float: left;
border:3px dashed black;
border-style:dashed;
}
JavaScript
//***************************************
// Initialize Map
//***************************************
function Initialize() {
var imagery = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers: [imagery],
view: new ol.View({
center: ol.proj.transform([-1.1833, 41.3833], 'EPSG:4326', 'EPSG:3857'),
zoom: 7
})
});
//Apply a filter on "postcompose" events.
imagery.on('postcompose', function(event) {
greyscale(event.context);
});
}
//***************************************
// Aux Func.
//***************************************
// function applies greyscale to every pixel in canvas
function greyscale(context) {
var canvas = context.canvas;
var width = canvas.width;
var height = canvas.height;
console.log('width: ' + width);
console.log('height: ' + height);
var inputData = context.getImageData(0, 0, width, height).data;
console.log('inputData.length: ' + inputData.length);
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.canvas.width = width;
ctx.canvas.height = height;
ctx.fillStyle = "rgba(0, 0, 0, 0)"
var myImageData = ctx.createImageData(ctx.canvas.width, ctx.canvas.height);
var d = myImageData.data;
for(i=0; i<inputData.length; i += 4){
var r = inputData[i];
var g = inputData[i + 1];
var b = inputData[i + 2];
// CIE luminance for the RGB
var v = 0.2126 * r + 0.7152 * g + 0.0722 * b;
d[i+0] = v*0; // Red
d[i+1] = v*0; // Green
d[i+2] = 255-v/4*3; // Blue
d[i+3] = 255; // Alpha
}
ctx.putImageData(myImageData,0,0);
}