简体   繁体   English

在同一个 canvas 中逆时针旋转 canvas 图像

[英]Rotate canvas image to anticlockwise in the same canvas

Say we have a canvas:假设我们有一个 canvas:

<canvas id="one" width="100" height="200"></canvas>

var canvas = document.getElementById("one");
var context = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;

// Sample graphic
context.beginPath();
context.rect(10, 10, 20, 50);
context.fillStyle = 'yellow';
context.fill();
context.lineWidth = 7;
context.strokeStyle = 'black';
context.stroke();

// create button
var button = document.getElementById("rotate");
button.onclick = function () {
  // rotate the canvas 90 degrees each time the button is pressed
  rotate();
}

var myImageData, rotating = false;

var rotate = function () {
  if (!rotating) {
    rotating = true;
    // store current data to an image
    myImageData = new Image();
    myImageData.src = canvas.toDataURL();

    myImageData.onload = function () {
      // reset the canvas with new dimensions
      canvas.width = ch;
      canvas.height = cw;
      cw = canvas.width;
      ch = canvas.height;

      context.save();
      // translate and rotate
      context.translate(cw, ch / cw);
      context.rotate(Math.PI / 2);
      // draw the previows image, now rotated
      context.drawImage(myImageData, 0, 0);
      context.restore();

      // clear the temporary image
      myImageData = null;

      rotating = false;
    }
  }
}

And on a button click the canvas gets rotated -90 degrees anticlockwise (around the centre) and the dimensions of the canvas get also updated, so in a sense, it looks like this afterwards: I want to rotate a canvas element to the anticlockwise rotation.然后在一个按钮上单击 canvas 逆时针旋转 -90 度(围绕中心),并且 canvas 的尺寸也得到更新,所以从某种意义上说,它看起来像这样:我想将 ZFCC790C72A86190DE1B549DDCDC655DE1B549DDC0 . I have used this code but it's not working as I want.我已经使用了这段代码,但它没有按我的意愿工作。

JavaScript has a built-in rotate() function for canvas context: JavaScript 有一个内置的rotate() function 用于 canvas 上下文:

context.rotate( angle * Math.PI / 180);

The problem is that the rotation will only affect drawings made AFTER the rotation is done, which means you will need to:问题是旋转只会影响旋转完成后制作的图纸,这意味着您需要:

  • Clear the canvas first: context.clearRect(0, 0, canvas.width, canvas.height);先清除canvas: context.clearRect(0, 0, canvas.width, canvas.height);
  • Rotate the context context.rotate( 270 * Math.PI / 180);旋转上下文context.rotate( 270 * Math.PI / 180);
  • Redraw the graphics重新绘制图形

Thus, I recommend wrapping the graphics we want to draw in a function to make it easier to call after every rotation:因此,我建议将我们要绘制的图形包装在 function 中,以便在每次旋转后更容易调用:

function drawGraphics() {
    context.beginPath();
    context.rect(10, 10, 20, 50);
    context.fillStyle = 'yellow';
    context.fill();
    context.lineWidth = 7;
    context.strokeStyle = 'black';
    context.stroke();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM