javascript - 通过 compose hooks 层旋转问题

标签 javascript openlayers-3

我正在开发一种工具来旋转静态图像层,但我目前在移动设备上遇到了问题。

静态图像层必须围绕特定点旋转。我使用预合成和后合成 Hook 来改变 Canvas 并进行旋转。 它在桌面上运行良好,但我不明白移动设备(Android Chrome 或 FF)上发生了什么。

jsFiddle:https://jsfiddle.net/wuty2m9v/7/

/* Vars */
const center = ol.proj.transform([1.44, 43.603], "EPSG:4326", "EPSG:3857")
const imgSize = [400, 267]
const imgExtent = [center[0], center[1], center[0] + imgSize[0], center[1] + imgSize[1]]
let rotation = 45

/* Init map */
const map = new ol.Map({
    target: 'map',
    view: new ol.View({
    zoom: 16,
    center,
  }),
  layers: [
    // Map tiles layer
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    // Feature layer
    new ol.layer.Vector({
        source: new ol.source.Vector({
        features: [
          new ol.Feature({
            geometry: new ol.geom.Point(center),
          }),
        ],
      }),
    }),
  ],
})

/* Init image layer */
const imgLayer = new ol.layer.Image({
  opacity: 0.7,
  source: new ol.source.ImageStatic({
    url: "https://pbs.twimg.com/profile_images/685220121598660608/2uZUdcS1.jpg",
    imageExtent: imgExtent,
  })
})
imgLayer.on("precompose", evt => {
  const pixel = map.getPixelFromCoordinate(center)
  const ctx = evt.context
  ctx.save()
  ctx.translate(pixel[0], pixel[1])
  ctx.rotate(rotation * Math.PI / 180)
  ctx.translate(-pixel[0], -pixel[1])
})
imgLayer.on("postcompose", evt => {
  const ctx = evt.context
  ctx.restore()
})
map.addLayer(imgLayer)

在桌面上,图像围绕该点正确旋转。拖动 map :点和图像跟随 map 。 在移动设备上,图像没有围绕该点正确旋转,它是围绕 Canvas 原点制作的, Canvas 平移看起来不太好。拖动 map 看乱象:)

最佳答案

在进行变换时,您需要考虑像素比率。您从 map.getPixelFromCoordinate 获得的像素是 css 像素。要获得 Canvas 像素,您需要将它们乘以 ol.has.DEVICE_PIXEL_RATIO:

ctx.translate(pixel[0] * ol.has.DEVICE_PIXEL_RATIO, pixel[1] * ol.has.DEVICE_PIXEL_RATIO);

ctx.translate(-pixel[0] * ol.has.DEVICE_PIXEL_RATIO, -pixel[1] * ol.has.DEVICE_PIXEL_RATIO);

参见 https://jsfiddle.net/wuty2m9v/8/获取 JSFiddle 的更新版本。

关于javascript - 通过 compose hooks 层旋转问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742809/

相关文章:

javascript - 启用询问使用 javascript/jquery 保存下载文件

openlayers-3 - 如何在 OpenLayers 3 中禁用 DragPan?

javascript - GeoServer - DWITHIN 未正确过滤点

Javascript从包含多个数组的对象获取平面数组

javascript - 继续运行进度条

php - 如何在不使用iframe的情况下在我们的网站中显示其他网站的内容?

javascript - 在 OpenLayer 中更平滑地加载图 block

openlayers - 更新到 OpenLayers 3

javascript - 如何将样式应用于 OpenLayers 3 中的修改交互?

javascript - Angularjs pubsub 与 $broadcast