如何通过javascript将图像/ HTML画布切成两半?

Tet*_*Dev 7 javascript jquery google-maps image html2canvas

我正在使用html2canvas将带有自定义功能的google地图javascript API转换为画布,然后转换为图像.

在所有浏览器上都能正常工作,除了在IE 11上它生成一个图像右侧有额外空白的图像,等于(浏览器窗口的宽度 - 地图宽度).所以我的窗户越宽,右边的空间越大,反之亦然.

如何将此图像(或HTMLcanvas)切割到实际图像的边缘(768像素宽)?

IE11图片

我在这里找到了这段代码,但不知道如何为此任务修改它:

var image = new Image();
image.onload = cutImageUp;
image.src = 'myimage.png';

function cutImageUp() {
    var imagePieces = [];
    for(var x = 0; x < numColsToCut; ++x) {
        for(var y = 0; y < numRowsToCut; ++y) {
            var canvas = document.createElement('canvas');
            canvas.width = widthOfOnePiece;
            canvas.height = heightOfOnePiece;
            var context = canvas.getContext('2d');
            context.drawImage(image, x * widthOfOnePiece, y * heightOfOnePiece, widthOfOnePiece, heightOfOnePiece, 0, 0, canvas.width, canvas.height);
            imagePieces.push(canvas.toDataURL());
        }
    }

    // imagePieces now contains data urls of all the pieces of the image

    // load one piece onto the page
    var anImageElement = document.getElementById('myImageElementInTheDom');
    anImageElement.src = imagePieces[0];
}
Run Code Online (Sandbox Code Playgroud)

wol*_*mer 6

这是创建图像的画布裁剪器。您需要调整地图的裁剪尺寸。

// initialize the test canvas and wireup cut button.
(function() {
  var can = document.getElementById('test');
  var w = can.width = 400;
  var h = can.height = 200;
  var ctx = can.getContext('2d');

  ctx.fillStyle = "#336699";
  ctx.fillRect(0, 0, 200, 200);
  ctx.strokeStyle = "#000000";
  ctx.lineWidth = 20;
  ctx.strokeRect(0, 0, w, h);
  ctx.strokeRect(0, 0, w / 2, h);
  var btn = document.getElementById('cut');
  btn.addEventListener('click', function() {
     
    var croppedCan = crop(can, {x: 0, y: 0}, {x: 200, y: 200});
    
    // Create an image for the new canvas.
    var image = new Image();
    image.src = croppedCan.toDataURL();
  
    // Put the image where you need to.
    document.getElementsByTagName('body')[0].appendChild(image);
    return image;
    
  });
})();


// function crop
// Returns a cropped canvas given a cavnas and crop region.
//
// Inputs:
// can, canvas
// a, {x: number, y: number} - left top corner
// b, {x: number, y: number} - bottom right corner

function crop(can, a, b) {
    // get your canvas and a context for it
    var ctx = can.getContext('2d');
    
    // get the image data you want to keep.
    var imageData = ctx.getImageData(a.x, a.y, b.x, b.y);
  
    // create a new cavnas same as clipped size and a context
    var newCan = document.createElement('canvas');
    newCan.width = b.x - a.x;
    newCan.height = b.y - a.y;
    var newCtx = newCan.getContext('2d');
  
    // put the clipped image on the new canvas.
    newCtx.putImageData(imageData, 0, 0);
  
    return newCan;    
 }
Run Code Online (Sandbox Code Playgroud)
<button id='cut'>Crop</button>
<hr/>
<canvas id='test'></canvas>
<hr/>
Run Code Online (Sandbox Code Playgroud)