js 画布翻转_将照片加载到画布中,然后翻转

js 画布翻转

js 画布翻转

zlati-nathalie.jpg

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标签翻转图像。 事实证明,是的,您可以,而且非常简单。

» Demo is here.

»演示在这里。

如何在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

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/photo-canvas-tag-flip/

js 画布翻转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值