javascript - 如何在不同方向多次绘制一张图像?

标签 javascript canvas html5-canvas

我有一个这样的数组,其想法是在不同方向输出图像,并通过缩放在 Canvas 上垂直和水平翻转它们。

[{  
  "pos":{  
      "x":411,
      "y":401.5
  },
  "scale":{  
      "x":1,
      "y":1
  }
},{  
  "pos":{  
      "x":411,
      "y":271.59625
  },
  "scale":{  
      "x":-1,
      "y":1
  }
}]

问题是我正在缩放 Canvas 而不是图像, Canvas 比我放置在其上的图像大几倍。

  images.forEach((image) => {
    // center borde köars innan loopen egentligen
    let pos = center(image.pos)
    cc.save()
    cc.scale(image.scale.x, image.scale.y)
    cc.drawImage(window.video, pos.x, pos.y)
    cc.restore()
  })

如何缩放图像(称为 window.video)而不是整个 Canvas ?

最佳答案

在 Canvas 上渲染缩放图像。

function drawImage(image,x,y,scaleX,scaleY){
    ctx.setTransform(scaleX, 0, 0, scaleY, x, y); // set scale and translation
    ctx.drawImage(image,0,0);
}

// when done drawing images you need to reset the transformation back to default
ctx.setTransform(1,0,0,1,0,0); // set default transform

如果您希望图像翻转但仍绘制在相同的左上角位置,请使用

function drawImage(image, x, y, scaleX, scaleY){
    ctx.setTransform(scaleX, 0, 0, scaleY, x, y); // set scale and translation
    x = scaleX < 0 ? -image.width : 0; // move drawing position if flipped
    y = scaleY < 0 ? -image.height : 0;
    ctx.drawImage(image, x, y);
}

并围绕图像的中心进行绘制

function drawImage(image, x, y, scaleX, scaleY){  // x y define center
    ctx.setTransform(scaleX, 0, 0, scaleY, x, y); // set scale and translation
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
}

关于javascript - 如何在不同方向多次绘制一张图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42492692/

相关文章:

html - 在 html 中飘扬的旗帜

javascript - 使用 Canvas 调整叠加图像的大小问题

javascript - 在 for 循环中使用临时变量

javascript - 怎么做才能点击显示内容部分?

javascript - 如何在 fabricjs 中设置选择的填充颜色?

javascript - 如何在不缩放内容的情况下更改 html5 Canvas 的尺寸

python - 如何在 tkinter 中动态调整 Canvas 中图像的大小?

javascript - 改进 three.js 场景中的光照

javascript - 如何在 js 数组中搜索?

javascript - Three.js 检测 webgl 支持并回退到常规 Canvas