0

I have a JavaScript generator which outputs black, grey and white square. How am I able to right click and save image of the generated image on the webpage?

HTML < button onclick="run()">Generate< /button>

function run() {

var x = document.getElementById("block");
if (x) {
    x.parentNode.removeChild(x);
}

var rows = 20;
var cols = 20;
var size = 30;

var container = document.createElement("div");
container.id = "block";

for (var i = 0, len = rows * cols; i < len; i++) {
    x = document.createElement("div");
    x.className = "cell";
    x.style.height = size + "px";
    x.style.width = size + "px";
    x.style.backgroundColor = pickColor();
    container.appendChild(x);
}
document.body.appendChild(container);
}
function pickColor(){
var colorArray = ["black", "grey", "white"];
return colorArray[Math.floor(Math.random() * colorArray.length)];
}
window.onload = run;
3
  • You are not creating an image here, all you are creating is a DIV with color. Commented Sep 29, 2015 at 4:15
  • Might be worth looking into server-side image generation. You can then serve the image to the client. Commented Sep 29, 2015 at 4:24
  • What's the purpose of this image? Do the squares need to be divs, or could you just do all of this in a canvas element? Commented Sep 29, 2015 at 4:37

1 Answer 1

2

You can use HTML2Canvas to generate a client-side image of your webpage (or part of it, for example your block element container).

html2canvas(container, { 
  onrendered: function(canvas) {
    var img_data_url = canvas.toDataURL("image/png");
    document.body.innerHTML += '<img src="' + img_data_url + '"/>';
  }
});

The above code will generate an image in an img tag of your generated HTML (and append it to your body). The user can then click "Save as" to save the image like he normally would do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.