javascript - 如何在 HTML5 Canvas 上翻转和旋转图像

标签 javascript node.js html html5-canvas electron

我正在构建一个 Electron 应用程序,它可以在工业打印机上布置用于批量打印的图像,但我遇到了图像翻转/镜像的问题。

这是我的代码,它确定图像是否应该翻转、旋转或两者兼而有之。

  _createClass(Image, null, [{
    key: 'drawRotatedImage',
    value: function drawRotatedImage(canvas, image, angle, mirrorImage) {
       var context = canvas.getContext('2d');
      if (angle > 0) {
        context.rotate(angle * (Math.PI / 180));
      }
      if (mirrorImage === true) {
        context.scale(-1, 1);
        context.drawImage(image, -image.width, -image.height, image.width, image.height);
      } else {
        context.drawImage(image, 0, angle === 0 ? 0 : -image.height);
      }
      return canvas;
    }
  },

代码的第一部分识别图像是否需要旋转。这很好用。然而,“mirrorImage”函数对于不需要旋转的图像无法正常工作。一切都在旋转的图像上完美运行。我错过了什么吗?任何人都可以帮忙吗,这已经让我发疯了好几个小时了。

谢谢

最佳答案

value: function drawRotatedImage(canvas, image, angle, mirrorImage) {
    var context = canvas.getContext('2d');
    if (angle > 0) {
        context.rotate(angle * (Math.PI / 180));
    }
    if (mirrorImage === true) {
        if (angle > 0) {
            context.scale(-1, 1);
            context.drawImage(image, -image.width, -image.height, image.width, image.height);
        }
    } 

    if (mirrorImage === true) {
        if (angle < 1) {
            context.scale(-1, 1);
            context.drawImage(image, -image.width, 0, image.width, image.height);
        }
    } else {
        context.drawImage(image, 0, angle === 0 ? 0 : -image.height);
    }
    return canvas;
}

关于javascript - 如何在 HTML5 Canvas 上翻转和旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766116/

相关文章:

javascript - 如何使用护照检查 react 组件上的isAuthenticated

javascript - 数据未使用 Handlebars 和expressnjs渲染

html - body 高度和页脚粘在底部的 CSS 问题

javascript - 跨域的 Backbone PUT 请求未将 id 附加到 URL

javascript - 在 vs 代码中将 emmet 与 react 应用程序一起使用不起作用

javascript - 模式 HTML/Javascript 中的无效转义

javascript - nodejs中的libuv线程如何利用多核cpu

javascript - 循环中的 Node URLSearchParams 删除不会删除所有条目

HTML 边框放置

javascript - 使用 jQuery,在元素上设置 Draggable 可防止在单击可拖动元素时触发模糊