From 10f9a70d5faada3e0f6685ed53a3bdac5fb938f5 Mon Sep 17 00:00:00 2001 From: mike-000 <49240900+mike-000@users.noreply.github.com> Date: Wed, 4 Dec 2019 22:59:16 +0000 Subject: [PATCH] Adjust for layer canvas pixel ratio and rotation --- examples/layer-clipping.js | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/examples/layer-clipping.js b/examples/layer-clipping.js index dc7a892dae..a6805fdac5 100644 --- a/examples/layer-clipping.js +++ b/examples/layer-clipping.js @@ -18,11 +18,17 @@ const map = new Map({ osm.on('prerender', function(event) { const ctx = event.context; + + // calculate the pixel ratio and rotation of the canvas + const matrix = event.inversePixelTransform; + const canvasPixelRatio = Math.sqrt(matrix[0] * matrix[0] + matrix[1] * matrix[1]); + const canvasRotation = -Math.atan2(matrix[1], matrix[0]); ctx.save(); - const pixelRatio = event.frameState.pixelRatio; - const size = map.getSize(); - ctx.translate(size[0] / 2 * pixelRatio, size[1] / 2 * pixelRatio); - ctx.scale(3 * pixelRatio, 3 * pixelRatio); + // center the canvas and remove rotation to position clipping + ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2); + ctx.rotate(-canvasRotation); + + ctx.scale(3 * canvasPixelRatio, 3 * canvasPixelRatio); ctx.translate(-75, -80); ctx.beginPath(); ctx.moveTo(75, 40); @@ -34,8 +40,11 @@ osm.on('prerender', function(event) { ctx.bezierCurveTo(85, 25, 75, 37, 75, 40); ctx.clip(); ctx.translate(75, 80); - ctx.scale(1 / 3 / pixelRatio, 1 / 3 / pixelRatio); - ctx.translate(-size[0] / 2 * pixelRatio, -size[1] / 2 * pixelRatio); + ctx.scale(1 / 3 / canvasPixelRatio, 1 / 3 / canvasPixelRatio); + + // reapply canvas rotation and position + ctx.rotate(canvasRotation); + ctx.translate(-ctx.canvas.width / 2, -ctx.canvas.height / 2); }); osm.on('postrender', function(event) {