javascript - 如何让我的画布图像每次旋转 90 度,它只旋转 180 度
问题描述
我试图让我的图像在你点击它时旋转 90 度,但它只旋转 180 度,我如何让它每次点击它时移动 90 度?
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Flipping photo in a canvas tag</title>
<style>
#canvas {cursor: pointer;}
canvas {
height: 50vh;
}
</style>
</head>
<body>
<label>Image File:</label>
<br/>
<input type="file" id="imageLoader" name="imageLoader" />
<h1>Example of using <code><canvas></code></h1>
<p>This example shows how a photo is loaded in a <code><canvas></code> tag and then flipped.</p>
<p>Click on the photo to flip (provided, of course, that your browser supports <code><canvas></code>)</p>
<canvas id="canvas" style="border:1px red solid;"></canvas>
<a download="new-image.png" id="download">Download</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
img.onload = function() {
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
ctx.save();
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
can.onclick = function() {
console.log('here');
ctx.translate(img.width - 1, img.height - 1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
var button = document.getElementById('download');
button.setAttribute( 'href', can.toDataURL('image/png', 1) );
};
</script>
<p><a href="http://www.phpied.com/photo-canvas-tag-flip/">Blog post is here</a></p>
</body>
</html>
解决方案
Math.PI
旋转 180°。n * Math.PI / 180
旋转n
°。所以在你的情况下,你需要调用ctx.rotate(Math.PI/2)
.
您的代码存在问题:您一直在移动旋转中心。因此,当您第二次旋转时,该中心已经远离原点。您现在平移这个(移动的)点,旋转它然后绘制。现在,您的新图像很可能在画布之外。
因此,您需要ctx.translate(img.width - 1, img.height - 1);
在旋转后撤消ctx.translate(-(img.width - 1), -(img.height - 1));
.
例子:
// Rotation by 90° around center at 150,75
ctx.translate(150, 75);
ctx.rotate(Math.PI / 2);
ctx.translate(-150, -75);
推荐阅读
- javascript - 使用javascript的字符串中存在单词
- r - googleway上的R“无法检索结果。没有有效的互联网连接”
- php - 使用覆盖一个 mySQL 表列和该行其余数据的表单
- android - Android - 如何接收快捷方式创建结果
- python - Bash 使用临时文件管道不允许重定向到依赖文件?
- java - 禁用更新的滚动 RecyclerView
- angular - ngFor多个上下文中的Angular 6 ngTemplateOutlet
- java - 问:在按钮单击时将笔划添加到圆形 TextView
- jquery - JQuery POST 返回状态码 200,但 Django 没有创建对象
- mysql - 使用 UNIXTIME 进行 MySQL 查询