user3299345
user3299345

Reputation: 97

Replace script genrated image inside canvas with usual jpeg

The script generates graphical data, then draws it on canvas as image, gets pixel data from that image, distorts it, then displays distorted results in real time on another canvas.

What I'm trying to do is to use an ordinary image as a data source to distort it and draw on another canvas. (I need to replace black and white tiles with picture)

Here is the fiddle

HTML:

    <canvas id="canvas"></canvas>

The function that generates graphical data which is transformed into image that is drawn on canvas:

function initSettings(settings) {
    var firstColorDef = 'black';
    var secondColorDef = 'white';
    var minCountDef = 16;
    firstColor = isColor(settings.firstColor) ? settings.firstColor : firstColorDef;
    secondColor = isColor(settings.secondColor) ? settings.secondColor : secondColorDef;
    minCount = settings.minCount > 0 ? settings.minCount : minCountDef;
    draw = settings.draw !== undefined ? settings.draw : false;
    }


    this.draw = function() {
    var step = Math.min(width, height) / minCount;
        var w = width / step, wf = Math.floor(w);
        var h = height / step, hf = Math.floor(h);
    var stepX = w === wf ? step : width / wf;
        var stepY = h === hf ? step : height / hf;
    
        for (var y = 0; y < hf; y++) {
        for (var x = 0; x < wf; x++) {
context.fillStyle = (y + x) % 2 === 0 ? firstColor : secondColor;
            context.fillRect(x * stepX, y * stepY, stepX, stepY);
            }
        }
};

If I try to replace it with something like this:

  var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var img = new Image();
        img.src = 'http://th01.deviantart.net/fs70/PRE/i/2010/310/1/c/andromeda_nebula_clean_by_rah2005-d329qyj.jpg';
        img.onload = function() { context.drawImage(img, 0, 0); }

Then even the canvas is not created, and firebug says that there is no script at all.

Any help is appreciated.

Upvotes: 0

Views: 66

Answers (1)

eithed
eithed

Reputation: 4320

Per discussion in comments, the issue lies with cross-origin policy as the canvas created needs to have source from within the same domain.

Bear in mind that you can try going against it, by using CORS as:

var img = new Image();
img.crossOrigin = "Anonymous";
img.src = "http://www.corsproxy.com/th01.deviantart.net/fs70/PRE/i/2010/310/1/c/andromeda_nebula_clean_by_ra‌​h2005-d329qyj.jpg";

and then constructing your canvas from such created image.

I've had mixed success with such approach (and can't really test it as the given image is no longer there).

Upvotes: 1

Related Questions