gpt4 book ai didi

javascript - 顺时针旋转 Canvas 90 度并更新宽度高度

转载 作者:搜寻专家 更新时间:2023-11-01 04:57:39 25 4
gpt4 key购买 nike

假设我们有一个 Canvas :

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

点击一个按钮, Canvas 会顺时针旋转 90 度(围绕中心), Canvas 的尺寸也会更新,所以从某种意义上说,之后它看起来像这样:

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

注意canvas的id是一样的

想象一下,简单地顺时针旋转图像而不对其进行裁剪或填充。

在创建新 Canvas 以及逐像素旋转和复制之前,有什么建议吗?

更新 带有评论建议的示例代码仍然无效:

function imageRotatecw90(){

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

var cw=canvas.width;
var ch=canvas.height;

var myImageData = context.getImageData(0,0, cw,ch);

context.save();

context.translate(cw / 2, ch / 2);
context.rotate(Math.PI/2);

context.putImageData(myImageData, 0, 0);

context.restore();

canvas.width=ch;
canvas.height=cw;
}

FiddleJS

最佳答案

看看这个DEMO .

为了实现演示中看到的结果,我使用 canvas.toDataURL 将 Canvas 缓存到图像中,然后将 Canvas 重置为新尺寸,正确地平移和旋转上下文,最后将缓存的图像绘制回修改后的 Canvas 。

这样您就可以轻松地旋转 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;
}
}
}

关于javascript - 顺时针旋转 Canvas 90 度并更新宽度高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16645801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com