如何利用HTML5 canvas旋转图片?(实例演示)

您所在的位置:网站首页 canvas如何旋转坐标系 如何利用HTML5 canvas旋转图片?(实例演示)

如何利用HTML5 canvas旋转图片?(实例演示)

#如何利用HTML5 canvas旋转图片?(实例演示)| 来源: 网络整理| 查看: 265

最近突然想研究一下js旋转图片的功能。对于之前的实现方式,就不先说了。现在HTML5很不错,主要了解一下HTML5中的图片旋转吧。

实例演示:

http://www.imqing.com/demo/rotateImg.html

原理:利用canvas对象来旋转。

实现方式:首先创建一个canvas元素,然后把img元素绘入canvas。但是,实际上,这是默认情况,就是图片没旋转时。如果图片要旋转90度的话,就需要先把canvas画布旋转90度后再绘图。

描述如下:

内部旋转原理是这样的,图片的坐标是从左上角开始计算,向右为x正方向,向下为y正方向,在旋转画布canvas时,实际上是这个坐标在旋转,所以最后绘图方式不一样。

当时我还用了picpick来测量旋转一定角度后起点坐标,才知道原来旋转是这样的。

代码:

向左旋转 向右旋转 function rotateImg(pid, direction) { //最小与最大旋转方向,图片旋转4次后回到原方向 var min_step = 0; var max_step = 3; var img = document.getElementById(pid); if (img == null)return; //img的高度和宽度不能在img元素隐藏后获取,否则会出错 var height = img.height; var width = img.width; var step = img.getAttribute('step'); if (step == null) { step = min_step; } if (direction == 'right') { step++; //旋转到原位置,即超过最大值 step > max_step && (step = min_step); } else { step--; step < min_step && (step = max_step); } img.setAttribute('step', step); var canvas = document.getElementById('pic_' + pid); if (canvas == null) { img.style.display = 'none'; canvas = document.createElement('canvas'); canvas.setAttribute('id', 'pic_' + pid); img.parentNode.appendChild(canvas); } //旋转角度以弧度值为参数 var degree = step * 90 * Math.PI / 180; var ctx = canvas.getContext('2d'); switch (step) { case 0: canvas.width = width; canvas.height = height; ctx.drawImage(img, 0, 0); break; case 1: canvas.width = height; canvas.height = width; ctx.rotate(degree); ctx.drawImage(img, 0, -height); break; case 2: canvas.width = width; canvas.height = height; ctx.rotate(degree); ctx.drawImage(img, -width, -height); break; case 3: canvas.width = height; canvas.height = width; ctx.rotate(degree); ctx.drawImage(img, -width, 0); break; } }

解释:canvas.width与height就不用解释了吧,应该。rotate应该也不用吧?关键是drawImage(img, x, y);

其中的x,y是指从哪一点开始画,因为整个坐标系统旋转了,所以,x,y不一样,比如step=1,图片向右旋转了90度,即坐标系旋转了90度,那么起始位置应该是x = 0, y= img.height

以上就是如何利用HTML5 canvas旋转图片?(实例演示)的详细内容,更多请关注php中文网其它相关文章!



【本文地址】


今日新闻


推荐新闻


    CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3