C.ZH
C.ZH

Reputation: 1

Javascript - Saving image on webpage

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;

Upvotes: 0

Views: 67

Answers (1)

mbinette
mbinette

Reputation: 5094

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.

Upvotes: 2

Related Questions