Comment puis-je extraire une partie d'une image dans un canevas et l'utiliser comme image de fond pour un div?

C'est comme ça que mon code ressemble:

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 + ')'); }); 

J'essaie d'extraire une partie de l'image sur toile, de (0,0) avec la hauteur et la largeur 300px, et convertir cet objet imageData en un DataUr pour être utilisé comme fond d'une div.

Je reçois une erreur: imageData.toDataUrl () n'est pas une fonction. Comment puis-je atteindre cet objectif?

Merci d'avance!

toDataURL est une méthode HTMLCanvasElement vous devez appeler à partir de l'élément toile lui-même.

Vous pouvez récupérer votre image résultanteData sur la toile après avoir changé sa taille pour la version recherchée, mais la solution la plus simple est d'utiliser une seconde toile hors écran, où vous dessinez la première toile grâce à la méthode context.drawImage :

 // 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>