javascript - How do I extract a portion of an image in canvas and use it as background image for a div? -


this how code looks:

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

i'm trying extract portion of image on canvas, (0,0) height , width 300px, , convert imagedata object dataurl used background of div.

i error: imagedata.todataurl() not function. how can achieve this?

thanks in advance!

todataurl htmlcanvaselement method have call canvas element itself.

you draw resulted imagedata canvas after changed size wanted one, easiest solution use second, off-screen canvas, draw first canvas context.drawimage method:

// crop function  var crop = function(canvas, offsetx, offsety, width, height, callback) {    // create in-memory canvas    var buffer = document.createelement('canvas');    var b_ctx = buffer.getcontext('2d');    // set width/height required ones    buffer.width = width;    buffer.height = height;    // draw main canvas on our buffer 1    // 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);    // call callback 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 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";    // dataurl of our cropped image  var callback = function(dataurl) {    document.body.style.backgroundimage = 'url(' + dataurl + ')';  }
<canvas id="main" width="284" width="383"></canvas>


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -