js 画布翻转
Today our family went to the yearly photo session with the girls. We took one shot that can be looked normally, as well as upside down, so I was wondering can you flip an image using a canvas tag. Turns out, yes, you can and it's pretty easy.
今天,我们一家与女孩们一起参加了年度合影。 我们拍摄了一张可以正常看以及颠倒的照片,所以我想知道您是否可以使用canvas标签翻转图像。 事实证明,是的,您可以,而且非常简单。
如何在canvas
标签中加载图像? (How to load an image in a canvas
tag?)
Start unpretentiously with an empty canvas
tag:
从一个空的canvas
标记毫不客气地开始:
<canvas id="canvas"></canvas>
Now the javascript. Two variables to store a handle to the canvas element and the 2D context of the canvas:
现在JavaScript。 两个变量用于存储canvas元素的句柄和canvas的2D上下文:
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
Now let's load an image into the canvas. Using the new Image()
constructor you can create an image object, then set its src
property to point to the location of the image file. Then set an onload
handler for the image which is an anonymous function to be called when the image is done loading. There you put the image inside the canvas using the drawImage()
method of the canvas context.
现在,将图像加载到画布中。 使用new Image()
构造函数,可以创建图像对象,然后将其src
属性设置为指向图像文件的位置。 然后为图像设置一个onload
处理程序,这是在完成图像加载onload
的匿名函数。 使用画布上下文的drawImage()
方法将图像放在画布中。
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'zlati-nathalie.jpg';
You can also notice how the dimensions of the canvas are adjusted to match the dimensions of the image.
您还可以注意到如何调整画布的尺寸以匹配图像的尺寸。
如何颠倒图像 (How to flip the image upside down)
The canvas context provides a rotate()
method. The rotation always happens around the top left corner of the image, so we first translate()
the image to the bottom right. This way when the image is rotated, it fits back into the canvas. (There is also a one pixel correction, I have no idea why, just saw that the image wasn't flipping exactly otherwise). Assigning this functionality to the onclick
:
canvas上下文提供了rotate()
方法。 旋转始终围绕图像的左上角进行,因此我们首先translate()
图像translate()
到右下角。 这样,当旋转图像时,它可以放回画布中。 (还有一个像素校正,我不知道为什么,只是看到图像没有完全翻转)。 将此功能分配给onclick
:
can.onclick = function() {
ctx.translate(img.width-1, img.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(img, 0, 0, img.width, img.height);
};
C'est tout! Once again, the demo is here.
Tell your friends about this post on Facebook and Twitter
在Facebook和Twitter上告诉您的朋友有关此帖子的信息
js 画布翻转