简体   繁体   English

HTML Canvas(SVG)-在圆柱面上绘制图像

[英]HTML Canvas (SVG) - Draw image on cylinder surface

I'm working with HTML5 Canvas now. 我正在使用HTML5 Canvas。 I have one image file and and a mug image file. 我有一个图像文件和一个杯子图像文件。 I want the image file to be drawn on that cylinder surface. 我希望将图像文件绘制在该圆柱面上。 Something like the images below. 如下图所示。

在此处输入图片说明在此处输入图片说明

Are there any Javascript canvas (or maybe SVG) libraries that can help me archive that? 是否有任何Javascript画布(或SVG)库可以帮助我存档?

Thank you very much 非常感谢你

You can achieve your "wrap" effect by slicing your image into 1px wide vertical slices and changing the "Y" coordinate of each slice to fit the curve of your cup. 通过将图像切成1px宽的垂直切片并更改每个切片的“ Y”坐标以适合您的杯子曲线,可以实现“包装”效果。

Here's example code that uses this technique to "stretch" an image. 这是使用此技术“拉伸”图像的示例代码。

Feel free to modify this code to fit along the curve of your cup. 随意修改此代码以适合您的杯子曲线。

在此处输入图片说明

Example code and a Demo: http://jsfiddle.net/m1erickson/krhQW/ 示例代码和演示: http : //jsfiddle.net/m1erickson/krhQW/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/warp.png";
    function start(){

        var iw=img.width;
        var ih=img.height;
        canvas.width=iw+20;
        canvas.height=ih+20;

        var x1=0;
        var y1=50;
        var x2=iw;
        var y2=0
        var x3=0;
        var y3=ih-50;
        var x4=iw;
        var y4=ih;

        // calc line equations slope & b (m,b)
        var m1=Math.tan( Math.atan2((y2-y1),(x2-x1)) );
        var b1=y2-m1*x2;
        var m2=Math.tan( Math.atan2((y4-y3),(x4-x3)) );
        var b2=y4-m2*x4;

        // draw vertical slices
        for(var X=0;X<iw;X++){
            var yTop=m1*X+b1;
            var yBottom=m2*X+b2;
            ctx.drawImage( img,X,0,1,ih, X,yTop,1,yBottom-yTop );
        }

        // outline
        ctx.beginPath();
        ctx.moveTo(x1,y1);
        ctx.lineTo(x2,y2);
        ctx.lineTo(x4,y4);
        ctx.lineTo(x3,y3);
        ctx.closePath();
        ctx.stroke();
    }

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM