如何使用画布分别操作图像切片?

时间:2015-07-29 12:37:01

标签: javascript html5 image-processing canvas

我不熟悉HTML中的“画布”术语。我将一张照片分成两半,在它们之间留下一个小间隙。我想分别旋转每一半以创建半折叠效果。

window.onload = function () {
            var myCanv = document.getElementById("myCanvas");
            var context = myCanv.getContext('2d');
            var myImage = document.getElementById("myImage");
            context.drawImage(myImage, 0, 0, myImage.width / 2, myImage.height, 0, 0, myCanv.width / 2, myCanv.height);
            context.drawImage(myImage, (myImage.width / 2) + 1, 0, myImage.width / 2, myImage.height, (myCanv.width / 2) + 0.5, 0, myCanv.width / 2, myCanv.height);
        };

有什么办法可以用帆布做到这一点吗?我感谢任何帮助。 :)

Here is a fiddle.我知道它并不多,但任何暗示都很有用。

1 个答案:

答案 0 :(得分:2)

你可能想要扭曲图像的两半而不是旋转它们。

为了倾斜,您可以使用context.transformcontext.setTransform

enter image description here

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var skewLeft=.1;
var skewRight=-.1;
var cx=100;
var y=30;
var iw,ih;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/cars.jpg";
function start(){
  iw=img.width;
  ih=img.height;
  draw();
}

function draw(){

  // fill the canvas background with gray
  ctx.fillStyle='gray';
  ctx.fillRect(0,0,cw,ch);
  ctx.fillStyle='black'

  // draw the left skewed page with a stroked border
  ctx.setTransform(1,skewLeft,0,1,cx,0);
  ctx.drawImage(img,0,0,iw/2,ih,-iw/2,y,iw/2,ih);
  ctx.strokeRect(-iw/2,y,iw/2,ih);
  ctx.setTransform(1,0,0,1,0,0);

  // draw the right skewed page with a stroked border
  ctx.setTransform(1,skewRight,0,1,cx,0);
  ctx.drawImage(img,iw/2,0,iw/2,ih,0,y,iw/2,ih);
  ctx.strokeRect(0,y,iw/2,ih);
  ctx.setTransform(1,0,0,1,0,0);
}
body{ background-color:white; }
img,#canvas{border:1px solid red;}
<h4>Original Image (left) and<br>Image halved, skewed & bordered to look like a fold</h4>
<img src='https://dl.dropboxusercontent.com/u/139992952/multple/cars.jpg'>
<canvas id="canvas" width=225 height=150></canvas>