在画布上绘制和旋转多个图像

问题描述

我想在画布上绘制四个图像,如下所示。

但是,我只想使用一张图像,而不是四张。

(仅使用img0,不使用img90 / img180 / img270)

换句话说,我想在画布上用一张图像(img0)绘制四个旋转方向不同的图像。

有可能吗?

var ctx = document.getElementById('canvas').getContext('2d')

var img0 = new Image()
img0.src = 'https://i.stack.imgur.com/0vxxK.png'
img0.addEventListener('load',function() {
  ctx.drawImage(img0,0)
},false);

var img90 = new Image()
img90.src = 'https://i.stack.imgur.com/9EgLn.png'
img90.addEventListener('load',function() {
  ctx.drawImage(img90,20,false);

var img180 = new Image()
img180.src = 'https://i.stack.imgur.com/Us9fa.png'
img180.addEventListener('load',function() {
  ctx.drawImage(img180,40,false);

var img270 = new Image()
img270.src = "https://i.stack.imgur.com/EO9f9.png"
img270.addEventListener('load',function() {
  ctx.drawImage(img270,60,false);
<canvas id="canvas" width="150" height="150"></canvas>

sample image degree 0

sample image degree 90

sample image degree 180

sample image degree 270

解决方法

有可能。您可以使用ctx.rotate("degrees" * Math.PI / 180);函数。将"degrees"替换为您要旋转图像的数量。