Canvas image crossplatform insecure error

I have this code for create canvas image from different server urls

function getBase64Image(imageUri) { 
    var canvas = document.createElement("canvas");
    ctx = canvas.getContext("2d"); 
    var img = new Image();
    img.src = imageUri;
    img.crossOrigin = "Anonymous";
    img.onload = function() {
       canvas.width = this.width;
       canvas.height = this.height;
       ctx.drawImage(img, 0, 0, this.width, this.height);
       var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
       var dataURL = canvas.toDataURL("image/png");
       document.getElementById("dummyhiddenField").value = dataURL;

Where I am trying to get image from server and set it's canvas url to hidden field but its working good with local image only

As per the other answers from stackoverflow i set crossOrigin = "Anonymous" which isn't working also not able to set access origin from server, Have to manage all the things from localscript




An updated look at Html5 Canvas with Cross-Domain content.

Here is an updated look at how cross-domain content affects the html5 canvas and how to work within the security restrictions that apply to cross-domain content

An update is useful today (2016-Jan) because there are several new(ish) methods to allow cross-domain images to be drawn to canvas without tainting the canvas.

Drawing cross-domain content on html5 canvas will cause it to be "tainted"

You can draw an image from another domain on the canvas and it will display on the canvas. Accessing resources from another domain is called "Cross Origin Resource Sharing" -- and is generally known as "CORS" for short.

Drawing CORS content (f.ex: images) will cause the canvas to be "tainted" for security reasons.

If the canvas is tainted you cannot use these canvas & context methods:

  • context.getImageData to fetch the pixel data on the canvas
  • canvas.toDataURL to export the canvas as an image

You can't "trick" canvas into violating its CORS security restrictions -- hopefully you wouldn't even want to try! But you can draw cross-origin images without tainting the canvas by satisfying CORS security restrictions.

The "usual" (and simplest) way of handling images so they don't taint the canvas:

Put your images in the same domain as the webpage. You can have several physical servers delivering content but the image domain must be the same as the html code (or the javascript code) that creates the canvas. CORS restrictions are satisfied and the canvas is not tainted.

Notes about CORS while you're developing on your own computer

Solution#1(!): You can install a web server on your dev computer and serve both the web page files (.html, .js, etc) and your image files (.png, .jpg, etc) from one domain.

The folders of your development computer are declared to be different domains. So drawing an image from a subdirectory on your local disk will violate CORS restrictions because different local folders are different domains.

Solution#2: While doing development, you can put both your webpage files and your image files on your desktop and the images will be declared to be in the same domain and your canvas will not be tainted.

Satisfying CORS restrictions when images are on different domains

Solution#3: You can use cross-domain images on canvas without tainting it. To do that, you must satisfy these requirements:

  • Clientside: The image object must have the crossOrigin attribute set to allow cross-origin content. This property can be set within the html element tag or within javascript. Enabling settings are "anonymous" and "use-credentials".

  • Serverside: The server must be configured to return header(s) indicating that the response contains authorized content.

More than 1 response header might be needed depending on configuration:

Access-Control-Allow-Origin will return either anonymous authorization (*) or will return specific authorization based on the request.

Access-Control-Allow-Credentials is required if authentication requires additional information (like cookies).

Access-Control-Expose-Headers gives the client access to additional response information.

Enabling cross-domain requests on the server can be complex, especially when serving content that is authorized based on client roles. For additional information about starting configuration, you can visit:

Using cross-domain image hosts that allow anonymous access to their images

Solution#4: Some public image hosts allow you to upload images which will be served to clients in a CORS compliant way. Several examples are: imgur and dropbox. Stackoverflow images are hosted on Imgur.

Here's an example of how to serve images on in a CORS compliant way:

  1. Sign up for a Dropbox Account.
  2. You are given several default folders. Upload your images in the special "Public" folder. This is the folder that Dropbox gives CORS compliant anonymous access.
  3. Right-click on an image you want to serve and select "Copy public link". Your clipboard will have a link to your CORS compliant image.
  4. Load the image onto your page with the img tag or in javascript.

Here's example code to get a CORS compliant image object from Dropbox using javascript:

var img=new Image();
function start(){
    // The canvas is not tainted so 
    // the following both work without errors
    var url=canvas.toDataURL();
    var imageData=context.getImageData(0,0,100,100);

New(ish): Satisfy CORS by having the clientside user give consent

CORS security restrictions are meant to stop bad people from secretly taking your information while leaving you unaware.

Until recently, browsers relied on client-server configuration to satisfy security requirements. Recently, browsers have begun allowing cross-origin content if the user is affirmatively involved in deciding what content is being used.

Solution#5: Chrome and Firefox now allow the client-user to right click the canvas & save the canvas as an image. This is the manual equivalent of using canvas.toDataURL to create an image object and save that image object to the local drive. CORS is satisfied because the user decided if the canvas content was appropriate to save to their local drive and they affirmatively right-click to initiate the download process.

Solution#6: You can use an input element, type='file' to let the client-user select an image. The user can even select an internet URL (http://...). Again, CORS is satisfied because the user is involved in the selection process.

Here's example code showing how to listen for the user to select an image using an input:

// canvas vars
var canvas=document.createElement("canvas");
var ctx=canvas.getContext("2d");

// define max resulting image width,height (after resizing)
var maxW=100;
var maxH=100;

// listen for user to select files
var input = document.getElementById('input');
input.addEventListener('change', handleFiles);

function handleFiles(e) {
  var img = new Image;
  img.onload = function(){
    var iw=img.width;
    var ih=img.height;
    // scale down, if necessary
    if(iw>maxW || ih>maxH){
      var scale=Math.min((maxW/iw),(maxH/ih));
    // set canvas width/height to scaled size
    // draw+scale the img onto the canvas
    // create a jpeg URL (with medium quality to save "weight") 
    var jpg=canvas.toDataURL('image/jpeg',0.60);
    // In Demo: add the jpg to the window
    // In production, accumulate jpg's & send to server
    $('<img />',{src:jpg}).appendTo('body');
  // In Demo: Just process the first selected file 
  // In production: process all selected files 
  img.src = URL.createObjectURL([0]);
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<script src=""></script>
<h4>You can even enter a web URI (http://...)</h4>
<input type="file" id="input"/><br>

Solution#7: You can use the new(ish) FileReader to let the user select image(s) to be drawn on the canvas.

// dropDiv event handlers
var dropDiv=document.getElementById("dropDiv");
dropDiv.addEventListener("dragenter", handleDragEnter, false);
dropDiv.addEventListener("dragover", handleDragOver, false);
dropDiv.addEventListener("drop", handleDrop, false);
function handleDragEnter(e) {
function handleDragOver(e) {
function handleDrop(e) {

  var dt = e.dataTransfer;
  var files = dt.files;


function handleFiles(files) {

  for (var i=0;i<files.length;i++) {
    var file = files[i];
    var imageType = /image.*/;

    if (!file.type.match(imageType)) {

    var img = document.createElement("img");
    img.file = file;

    var reader=new FileReader();
      return function(e) {
          var canvas=document.createElement("canvas");
          var ctx=canvas.getContext("2d");
        // is a dataURL for the image
        aImg.src =;

  } // end for

} // end handleFiles

function calcNewAspect(imgWidth, imgHeight, maxWidth, maxHeight) {
  var ratio = Math.min(maxWidth/imgWidth,maxHeight/imgHeight);
  return {width:imgWidth*ratio,height:imgHeight*ratio };
body{ background-color: ivory; }
canvas{border:1px solid red;}
#dropDiv{border:1px solid blue; width:300px;height:300px;}
<script src=""></script>
<h4>Drag 1+ image(s) from desktop to blue dropDiv.</h4>
<div id="dropDiv"></div>
<div id="preview"></div>

To be continued...

There are likely more info-bits that need to be included in this update. Please feel free to comment on my absent mindedness and I'll continue the update. :-)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.