openlayers实现截屏并将图片转化为二进制存储到后台服务器

67 阅读1分钟
captureScreenshot() {
  var that = this;
  let stopLoading = this.$Message.loading({
    content: this.$t("x_save_project_cover") + "",
    duration: 0,
  });
  this.map.once("rendercomplete", () => {
    const mapCanvas = document.createElement("canvas");
    const size = that.map.getSize();
    mapCanvas.width = size[0];
    mapCanvas.height = size[1];
    const mapContext = mapCanvas.getContext("2d");
    Array.prototype.forEach.call(
      that.map
        .getViewport()
        .querySelectorAll(".ol-layer canvas, canvas.ol-layer"),
      function (canvas) {
        if (canvas.width > 0) {
          const opacity =
            canvas.parentNode.style.opacity || canvas.style.opacity;
          mapContext.globalAlpha = opacity === "" ? 1 : Number(opacity);
          let matrix;
          const transform = canvas.style.transform;
          if (transform) {
            // Get the transform parameters from the style's transform matrix
            matrix = transform
              .match(/^matrix\(([^\\(]*)\)$/)[1]
              .split(",")
              .map(Number);
          } else {
            matrix = [
              parseFloat(canvas.style.width) / canvas.width,
              0,
              0,
              parseFloat(canvas.style.height) / canvas.height,
              0,
              0,
            ];
          }
          // Apply the transform to the export map context
          CanvasRenderingContext2D.prototype.setTransform.apply(
            mapContext,
            matrix
          );
          const backgroundColor = canvas.parentNode.style.backgroundColor;
          if (backgroundColor) {
            mapContext.fillStyle = backgroundColor;
            mapContext.fillRect(0, 0, canvas.width, canvas.height);
          }
          mapContext.drawImage(canvas, 0, 0);
        }
      }
    );
    mapContext.globalAlpha = 1;
    mapContext.setTransform(1, 0, 0, 1, 0, 0);
    mapCanvas.toBlob(function (blob) {
      let file = new File([blob], "image", {
        lastModified: new Date().getTime(),
      });
      let formData = new FormData();
      formData.append("file", file);
      formData.append("workspaceId", Number(that.wid));
      update("/workspace/update/preview", formData).then((res) => {
        if (res.code == 0) {
          setTimeout(() => {
            stopLoading();
            that.toPath("project-scene");
          }, 1000);
        }
      });
    });
  });
  this.map.renderSync();
},

需要注意的是,在添加跨域图层的时候 mapCanvas.toBlob方法会报错:“无法加载跨域图像资源”这时候的解决办法

new TileLayer({ source: new XYZ({ url,  crossOrigin: 'anonymous', }) });

添加crossOrigin: 'anonymous'即可解决报错