JavaScript画布图像转换

At last week's Mozilla WebDev Offsite, we all spent half of the last day hacking on our future Mozilla Marketplace app. One mobile app that recently got a lot of attention was Instagram, which sold to Facebook for the bat shit crazy price of one billion dollars. Since I wouldn't mind having a bill in my back account, I decided to create an Instagram-style app (which I'll share with you in the future). This post details how you can convert an image to canvas and convert a canvas back to an image.

在上周的Mozilla WebDev Offsite上,我们所有人都花了最后一天的一半时间来开发我们未来的Mozilla Marketplace应用。 Instagram是最近受到广泛关注的一个移动应用,Instagram卖给了Facebook, 蝙蝠狗屎疯了 价格十亿美元。 由于我不介意在自己的后帐户中结账,因此我决定创建一个Instagram风格的应用(以后会与您分享)。 这篇文章详细介绍了如何将图像转换为画布,以及如何将画布转换回图像。

使用JavaScript将图像转换为Canvas (Convert an Image to Canvas with JavaScript)

To convert an image to canvas, you use a canvas element's context's drawImage method:

要将图像转换为画布,请使用画布元素的上下文的drawImage方法:


// Converts image to canvas; returns new canvas element
function convertImageToCanvas(image) {
	var canvas = document.createElement("canvas");
	canvas.width = image.width;
	canvas.height = image.height;
	canvas.getContext("2d").drawImage(image, 0, 0);

	return canvas;
}


The 0, 0 arguments map to coordinates on the canvas where the image data should be placed.

0, 0参数映射到画布上应放置图像数据的坐标。

使用JavaScript将画布转换为图像 (Convert Canvas to an Image with JavaScript)

Assuming modifications to the image have been made, you can easily convert the canvas data to image data with the following snippet:

假设已对图像进行了修改,则可以使用以下代码片段轻松地将画布数据转换为图像数据:


// Converts canvas to an image
function convertCanvasToImage(canvas) {
	var image = new Image();
	image.src = canvas.toDataURL("image/png");
	return image;
}


The code above magically converts the canvas to a PNG data URI!

上面的代码神奇地将画布转换为PNG数据URI!

Alas, converting an image to canvas and canvas to an image is probably much easier than you think. In future posts, I'll detail how you can apply different image filters to your canvased image. In the mean time, start buying fancy cars and houses with the future billion you'll have!

,,将图像转换为画布并将画布转换为图像可能比您想象的要容易得多。 在以后的文章中,我将详细介绍如何将不同的图像滤镜应用于画布图像。 同时,开始购买您未来将拥有的数十亿美元的高档汽车和房屋!

翻译自: https://davidwalsh.name/convert-canvas-image

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值