SkullDev SkullDev - 1 year ago 104
Javascript Question

Chrome not rendering canvas data as expected [JS/Canvas API]

I have a function which I have altered from an answer on codegolf (since the original answer didn't actually work).

Basically all it does is takes the pixels of an image, scrambles them up and then outputs the scrambled image onto the page.

Here is my code as it stands:

<!DOCTYPE html>
<html lang="en">

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
img {
min-width: 500px;
min-height: 500px;

<img src="test.jpg" alt="" />
function scramble(el) {
"use strict";
var V = document.createElement('canvas');
var W = V.width = el.width,
H = V.height = el.height,
C = V.getContext('2d');

C.drawImage(el, 0, 0);

var id = C.getImageData(0, 0, W, H),
D =,
L = D.length,
i = L / 4,
A = [];

for (; --i;) A[i] = i;

function S(A) {
var L = A.length,
x = L >> 3,
y, t, i = 0,
s = [];

if (L < 8) return A;

for (; i < L; i += x) s[i / x] = S(A.slice(i, i + x));

for (i = 4; --i;) y = [6, 4, 7, 5, 1, 3, 0, 2][i], t = s[i], s[i] = s[y], s[y] = t;

s = [].concat.apply([], s);

return s;
var N = C.createImageData(W, H),
d =,
A = S(A);

for (var i = 0; i < L; i++) d[i] = D[(A[i >> 2] * 4) + (i % 4)];

C.putImageData(N, 0, 0);

el.src = C.canvas.toDataURL("image/jpeg", 1.0);



Now, the issue is with chrome, unlike FF, Edge and IE, which all display as expected, chrome just shows a black square where the image should be.

I can't for the life of me figure out why, especially since all the other browsers work as expected.

Here is a screenshot of the other browsers showing fine and chrome with the black square.

enter image description here

As you can see, all of the other browsers are fine, chrome however just doesn't do as expected, nor does it throw any console errors or have any visible telltale reason for not working which is frustrating.

Anyway, any questions, ask below in the comments.

Answer Source

Try calling scramble at load event of <img> element

    document.querySelector("img").onload = function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download