I want to create a black (or white, I really don't care the "colour") 1x1px image in javascript, I tried doing it with var img = new Image(1,1)
but I don't know how assigng the source of the image with img.src
to be all black (I don't want to use a file, I want to be generated with JS code).
There is a way to do that?
CodePudding user response:
I found it:
var image = document.createElement('canvas').getContext('2d').getImageData(0,0,1,1);
I'll let question open to know if there is another way to do it.
Sources I used:
CodePudding user response:
Similarly you can perform the image manipulation in canvas, then pass a data URI containing a representation of the image over to the HTML image for actual rendering.
const imgWidth = 1;
const canvas = document.createElement("canvas");
canvas.width = imgWidth;
canvas.height = imgWidth;
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0,0,imgWidth,imgWidth);
const url = canvas.toDataURL();
const newImg = document.createElement("img");
newImg.src = url;
document.body.insertBefore(newImg, null);
CodePudding user response:
You can also use base64 encoded
data in the image.src
.
var image = new Image(10, 10);
image.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk A8AAQUBAScY42YAAAAASUVORK5CYII=";
document.body.appendChild(image);