javascript - Tainted canvas error thrown when refreshing the page with F5 -
i have problem code, quite similar codepen.
var img = new image(); img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/diceros_bicornis.jpg/320px-diceros_bicornis.jpg'; img.crossorigin = "anonymous" var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); img.onload = function() { ctx.drawimage(img, 0, 0); img.style.display = 'none'; }; var color = document.getelementbyid('color'); function pick(event) { var x = event.layerx; var y = event.layery; var pixel = ctx.getimagedata(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ', ' + data[1] + ', ' + data[2] + ', ' + (data[3] / 255) + ')'; color.style.background = rgba; color.textcontent = rgba; } canvas.addeventlistener('mousemove', pick);
<!-- learn code on mdn: https://developer.mozilla.org/en-us/docs/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas --> <canvas id="canvas" width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div>
it somehow works when page first open. when refresh page f5, sometimes starts throwing tainted canvas error. when click x close tab, , click link again open brand new tab work again.
i have img.crossorigin = "anonymous"
.
that sounds chrome bug, workaround-able : set crossorigin
attribute first.
the first time request made, crossorigin attribute set before image has loaded, hence browser redo request.
but when reload page, image cached, , loads before crossorigin attribute set. canvas tainted.
for similar little bugs cases, should define onload
event handler before setting src
attribute :
var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var img = new image(); img.crossorigin = "anonymous" img.onload = function() { ctx.drawimage(img, 0, 0); img.style.display = 'none'; }; // set src last img.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/diceros_bicornis.jpg/320px-diceros_bicornis.jpg'; var color = document.getelementbyid('color'); function pick(event) { var x = event.layerx; var y = event.layery; var pixel = ctx.getimagedata(x, y, 1, 1); var data = pixel.data; var rgba = 'rgba(' + data[0] + ', ' + data[1] + ', ' + data[2] + ', ' + (data[3] / 255) + ')'; color.style.background = rgba; color.textcontent = rgba; } canvas.addeventlistener('mousemove', pick);
<!-- learn code on mdn: https://developer.mozilla.org/en-us/docs/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas --> <canvas id="canvas" width="300" height="227" style="float:left"></canvas> <div id="color" style="width:200px;height:50px;float:left"></div>
Comments
Post a Comment