如何使用html5画布将图像叠加在杯子上 [英] How overlay image over a cup using html5 canvas

查看:170
本文介绍了如何使用html5画布将图像叠加在杯子上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是HTML5画布的新手。我有一个杯子的图像,我在画布上呈现。

I am new to HTML5 canvas. I have a image of a cup, I am rendered that in canvas.

这是杯子的图像:

现在我正在尝试在上传您的此图像的设计区域时,渲染另一个图像(我的正常矩形大小的照片)。如何在杯子上渲染看起来像这个图像的图像?

Now I am trying render another image (My photo that is in normal rectangular size) in upload your design area of this image. How can I render this image which looks like that image on cup?

我想得到这样的最终图像:

I want to get the final image like this :

I我使用canvas元素上传图片。

I am uses canvas element to upload the image.

 <!DOCTYPE html>
 <html>
 <body>

 <canvas id="myCanvas" width="400" height="400" style="border:5px solid #c3c3c3;">
 Your browser does not support the HTML5 canvas tag.
 </canvas>

 <script src="js/test.js" type="text/javascript"></script>


 </body>
 </html> 

JS

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();

var x = 0;
var y = 0;
var width = 290;
var height = 297;

imageObj.onload = function() {
    context.drawImage(imageObj, x, y);
};

imageObj.src = 'images/cup.jpg';


推荐答案

您希望第二张图片扭曲并出现仿佛它缠绕在杯子周围。

You want your second image to "warp" and appear as if it's wrapped around the cup.

你无法使用开箱即用的上下文2d将你的第二张图像变形为曲线图像

使用html Canvas 2d Context,你只能进行四边形偏移。因此,在倾斜图像之后,每个相对侧将始终平行。

Using html Canvas 2d Context, you can only do quadrilateral skewing. Therefore, after skewing an image each opposing side will always be parallel.

因此,您无法使用开箱即用的上下文2d将图像变形为弯曲图像。

Therefore, you cannot get your image to warp into a curved image using "out-of-the-box" context 2d.

一些解决方法......您可以使用屏幕外临时画布将第二个图像扭曲成曲线。然后,您可以使用context.drawImage在杯形图像的顶部绘制该曲线图像。以下是两种可以伪造图像曲率的选项。

A few workarounds...You can use an offscreen temporary canvas to "warp" your second image into a curve. Then you can draw that curved image on top of the cup image using context.drawImage. Here are 2 alternatives that let you "fake" curvature of an image.

备选方案#1:纹理映射

您可以使用纹理贴图将透视曲率应用于第二张图像:

You can use texture mapping to apply perspective curvature to your second image:

http://archive.gamedev.net/archive/reference/articles/article852.html

备选方案#2:垂直切片和拉伸

您可以垂直切片第二张图片以创建透视曲率。您可以使用context.drawImage的大小调整功能将像素拉伸到您的弯曲形状,就像之前的Stackoverflow答案一样:如何在HTML5(或Fabric.js)中制作屋顶文字效果和谷文字效果

You can vertically slice your second image to create perspective curvature. You can use the resizing capability of context.drawImage to "stretch" pixels into your curved shape like in this previously Stackoverflow answer: How to make rooftext effect and valley text effect in HTML5 (or Fabric.js)

jsfiddle.net/AbdiasSoftware/e8hZy /

jsfiddle.net/AbdiasSoftware/e8hZy/

这篇关于如何使用html5画布将图像叠加在杯子上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆