如何在画布中提取图像的一部分并将其用作div的背景图像?

时间:2016-01-27 09:26:22

标签: javascript html5 canvas data-url

这是我的代码的外观:

document.addEventListener('DOMContentLoaded', function () {
        var canvas = document.querySelector('canvas');
        var ctx = canvas.getContext("2d");
        var imageData = ctx.getImageData(0, 0, 300, 300);
        var tile = {
                        'id': 1,
                        'data': imageData,
                        'dataUrl': imageData.toDataUrl()
                    };
        var div = document.createElement('div');
                div.classList.add('tile');
                grid.appendChild(div);
                div.style.backgroundImage = ('url(' + tile.dataUrl + ')');
});

我尝试从(0,0)高度和宽度为300px的画布中提取部分图像,并将该imageData对象转换为dataUrl以用作div的背景。

我收到错误:imageData.toDataUrl()不是函数。我怎样才能做到这一点?

提前致谢!

1 个答案:

答案 0 :(得分:8)

toDataURL是一种HTMLCanvasElement方法,您必须从canvas元素本身调用它。

您可以在将大小更改为所需的大小后将生成的imageData绘制回画布,但最简单的解决方案是使用第二个屏幕外画布,您将在其中绘制第一个画布,这要归功于{{ 3}}方法:



// The crop function
var crop = function(canvas, offsetX, offsetY, width, height, callback) {
  // create an in-memory canvas
  var buffer = document.createElement('canvas');
  var b_ctx = buffer.getContext('2d');
  // set its width/height to the required ones
  buffer.width = width;
  buffer.height = height;
  // draw the main canvas on our buffer one
  // drawImage(source, source_X, source_Y, source_Width, source_Height, 
  //  dest_X, dest_Y, dest_Width, dest_Height)
  b_ctx.drawImage(canvas, offsetX, offsetY, width, height,
                  0, 0, buffer.width, buffer.height);
  // now call the callback with the dataURL of our buffer canvas
  callback(buffer.toDataURL());
};


// #main canvas Part

var canvas = document.getElementById('main');
var img = new Image();
img.crossOrigin = "Anonymous";

img.onload = function() {
  canvas.width = this.width;
  canvas.height = this.height;
  canvas.getContext('2d').drawImage(this, 0, 0);
  // set a little timeout before calling our cropping thing
  setTimeout(function() {
    crop(canvas, 100, 70, 70, 70, callback)
  }, 1000);
};

img.src = "https://dl.dropboxusercontent.com/s/1alt1303g9zpemd/UFBxY.png";

// what to do with the dataURL of our cropped image
var callback = function(dataURL) {
  document.body.style.backgroundImage = 'url(' + dataURL + ')';
}

<canvas id="main" width="284" width="383"></canvas>
&#13;
&#13;
&#13;