Как повернуть существующий контент холста HTML5? - PullRequest
4 голосов
/ 15 декабря 2011

Есть ли способ повернуть существующее содержимое холста HTML5 с помощью Javascript?Я знаю, что можно повернуть изображение, которое будет нарисовано на холсте, но я хочу повернуть содержимое, нарисованное на холсте, например, угол 200x200 холста 400x400 или любую конкретную область существующего холста..

Тот же вопрос для масштабирования существующего содержимого холста ...

Я знаю, что getImageData / putImageData обеспечивают возможность преобразования массива пикселей, но он слишком медленный и неэффективный.

Ответы [ 2 ]

11 голосов
/ 15 декабря 2011

Это довольно легко сделать с временным холстом.

Демонстрация в реальном времени

Анимированная демоверсия Live (просто так)

Приведенный выше пример рисует 2 поля, затем поворачивается и масштабируется от 0,0 до 200 200

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = canvas.height = 400;

// fill the canvas black, and draw 2 boxes
ctx.fillStyle = "#000";
ctx.fillRect(0,0,400,400);
ctx.fillStyle = "rgb(255,0,0)";

ctx.fillRect(10,10,190,190);
ctx.fillStyle = "rgb(255,255,0)";
ctx.fillRect(250,250,90,90);

// Create a temp canvas to store our data (because we need to clear the other box after rotation.
var tempCanvas = document.createElement("canvas"),
    tempCtx = tempCanvas.getContext("2d");

tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
// put our data onto the temp canvas
tempCtx.drawImage(canvas,0,0,canvas.width,canvas.height);

// Append for debugging purposes, just to show what the canvas did look like before the transforms.
document.body.appendChild(tempCanvas);

// Now clear the portion to rotate.
ctx.fillStyle = "#000";
ctx.fillRect(0,0,200,200);
ctx.save();
// Translate (190/2 is half of the box we drew)
ctx.translate(190/2, 0);
// Scale
ctx.scale(0.5,0.5);  
// Rotate it
ctx.rotate(45*Math.PI/180);
// Finally draw the image data from the temp canvas.
ctx.drawImage(tempCanvas,0,0,200,200,10,10,190,190);
ctx.restore();
5 голосов
/ 15 декабря 2011

Если вы сначала хотите нарисовать на canvas, а затем повернуть его для использования, например, на углах, вы можете сделать это, когда вы «клонируете» холст или с помощью CSS.

Примеры

Получить первый элемент холста:

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

нарисовать на нем:

ctx.fillStyle = 'blue';
ctx.fillRect(0,0, 25, 5);
ctx.fill();
ctx.fillStyle = 'red';
ctx.fillRect(25, 0, 25, 5);
ctx.fill();

клонировать его на другой холст (который вращается с помощью CSS):

var ctx2 = document.getElementById("canvas2").getContext("2d");
ctx2.drawImage(canvas, 0,0);

или вращайте холст, пока вы его «клонируете»:

var ctx3 = document.getElementById("canvas3").getContext("2d");
ctx3.rotate(Math.PI/2);
ctx3.translate(0,-50);
ctx3.drawImage(canvas, 0,0);

вот CSS для его поворота:

#canvas2 {
    -webkit-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -ms-transform:rotate(90deg);
}

enter image description here

Вот полный пример:

<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = 'blue';
    ctx.fillRect(0,0, 25, 5);
    ctx.fill();
    ctx.fillStyle = 'red';
    ctx.fillRect(25, 0, 25, 5);
    ctx.fill();

    var ctx2 = document.getElementById("canvas2").getContext("2d");
    ctx2.drawImage(canvas, 0,0);

    var ctx3 = document.getElementById("canvas3").getContext("2d");
    ctx3.rotate(Math.PI/2);
    ctx3.translate(0,-50);
    ctx3.drawImage(canvas, 0,0);

}
</script>
<style>
#canvas2 {
    -webkit-transform:rotate(90deg);
    -moz-transform:rotate(90deg);
    -o-transform:rotate(90deg);
    -ms-transform:rotate(90deg);
}
</style>
</head>
<body>
<canvas id="canvas" width="50" height="50"></canvas>
<canvas id="canvas2" width="50" height="50"></canvas>
<canvas id="canvas3" width="50" height="50"></canvas>
</body>
</html>
...