Related
I'm trying to code the Mandelbrot set as a fun project. I did it on my own, so it probably isn't optimized very well. I have a few questions about how to make my code better and how to add certain things to it. I used the library p5js, but that probably doesn't matter. (My code is at the bottom.)
First of all, when I render the set, the edges are very sharp. For example: See how the edges are sharp, because it operates pixel by pixel. However, I see in, for example, the Wikipedia page that it is possible to blend pixels and give more detail to the picture. How might I go about doing this? I've thought about calculating four values for each pixel, and blending them, but I feel like there should be another way.
Secondly, rendering the set takes much longer than it can if I want to animate it. I have to iterate more and more the more I zoom, so each frame would end up taking entire minutes to render. However, then I see videos like this https://www.youtube.com/watch?v=LhOSM6uCWxk or this https://www.youtube.com/watch?v=b005iHf8Z3g and I'd like to know how they are able to render these in less than a century. Is there an optimization method that I'm missing out on?
Another thing about the videos is how they are colored. For example, the first video I showed seemed like the colors were moving around everywhere, instead of staying in a constant spot, like the second video. What is the coloring method?
I've tried making the iterations low, but then I lose quality. I've tried an array of colors, but then it looks flat, like the second video. I want to know what's going on that I'm missing. I've looked at other solutions and seen that some people are rendering one pixel at a time, and that's what is making it slow. I do rows at a time for speed. All in all, what should I change to animate a set that looks pretty cool?
Finally, is there anything else that I should know to make my Mandelbrot set look amazing? Is there a completely different method for rendering that I should know? How is the first video made to look 3D? All of these clarifications would be nice to know.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/addons/p5.sound.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.3.0/math.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<main>
</main>
<script src="sketch.js"></script>
</body>
</html>
//noprotect
var y = 0;
var ratio;
var xstart = -2;
var xend = 2;
var ystart = -2;
var yend = 2;
var maxiter = 100;
var _xstart;
var _xend;
const colors = [
"rgb(255, 0, 255)",
"rgb(255, 0, 127)",
"rgb(255, 0, 0)",
"rgb(255, 127, 0)",
"rgb(255, 255, 0)",
"rgb(127, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 127)",
"rgb(0, 255, 255)",
"rgb(0, 127, 255)",
"rgb(0, 0, 255)",
"rgb(127, 0, 255)"
];
function setup() {
noStroke();
createCanvas(window.innerWidth, window.innerHeight);
ratio = width/height;
background(0);
_xstart = xstart * (width/height);
_xend = xend * (width/height);
_xstart = (xstart + xend)/2 + xstart*(width/height);
_xend = (xstart+xend)/2 + xend*(width/height);
}
function mandelbrot(rconst, iconst) {
var iter = math.complex(0, 0);
var current = 0;
for(var i = 0; i < maxiter; i ++) {
iter = iter.pow(2);
iter = iter.add(rconst, iconst);
current ++;
if(sqrt(pow(iter.re, 2)+pow(iter.im, 2)) > 2) {
break;
}
}
if(current === maxiter) {
return(0);
} else {
//color array
return(colors[(current) % colors.length]);
//purple
var temp = floor(map(current, 0, maxiter/3, 0, 255));
if(temp > 255) {
temp = 255;
}
// return('rgb(' + temp + ', 0, ' + temp + ')')
//black and white
// return(map(current, 0, 30, 0, 255))
return('rgb(0, 0, ' + temp + ')')
}
}
function draw() {
if(y < height+1) {
for(var x = 0; x < width+1; x ++) {
fill(mandelbrot(map(x, 0, width, _xstart, _xend), map(y, 0, height, ystart, yend)))
rect(x, y, 1, 1);
}
y++;
}
fill(0);
rect(0, 0, 300, 15);
fill(255);
text("x: " + map(mouseX, 0, width, _xstart, _xend) + ", y: " + map(mouseY, 0, height, ystart, yend), 0, 10);
}
I am trying to present this shape as a stimulus in a behavioral experiment. I wantthe image to have a random contrast level between 0 and 1. I am trying to use Math.random() for that but when I run this in Chrome the shape flickers when it is presented on the screen. Is there a way to present a stable shape with randomly generated contrast levels?
drawFunc: function gabor() {
context = jsPsych.currentTrial().context;
context.beginPath();
const gradLength = 100;
const my_gradient = context.createLinearGradient(850, 0, 1050, 0);
my_gradient.addColorStop(0,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.05,'rgb(255, 255, 255)');
my_gradient.addColorStop(0.1,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.15,'rgb(255, 255, 255)');
my_gradient.addColorStop(0.2,'rgb(0, 0, 0)');
my_gradient.addColorStop(0.25,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.3,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.35,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.4,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.45,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.5,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.55,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.6,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.65,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.7,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.75,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.8,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.85,"rgb(255, 255, 255)");
my_gradient.addColorStop(0.9,"rgb(0, 0, 0)");
my_gradient.addColorStop(0.95,"rgb(255, 255, 255)");
my_gradient.addColorStop(1,"rgb(0, 0, 0)");
var result1 = Math.random();
context.filter = 'contrast('+ result1 +')';
context.fillStyle=my_gradient;
context.fillRect(950,300,gradLength,gradLength);
context.stroke();
Use a setup function to get the constants
Create the gradient once
Get the context once.
Create contrast once using a function. See example
Remove setup code from draw function.
Remove random contrast value from draw function.
Remove redundant code
No need for context.beginPath(); as you draw the using fillRect
No need for context.stroke(). Not sure why you are calling stroke as you have not defined a path after the beginPath call
Why assign a named function gabor to object property drawFunc Do you call the function using its name or the property. Which ever you use makes the other redundent.
Example
setup() {
this.ctx = jsPsych.currentTrial().context;
const g = this.gradient = this.ctx.createLinearGradient(850, 0, 1050, 0);
const bands = 10, colors = ["#000", "#FFF"];
const stops = bands * colors.length;
var pos = 0;
while (pos <= stops) {
g.addColorStop(pos / stops, colors[pos % colors.length]);
pos++;
}
},
randomContrast() {
this.contrast = Math.Random();
this.drawFunc();
},
drawFunc() {
const ctx = this.ctx;
ctx.filter = 'contrast('+ this.contrast +')';
ctx.fillStyle = this.gradient;
ctx.fillRect(950, 300, 100, 100);
},
Call setup once, then call randomContrast to change the contrast. If you need to redraw the gradient without changing the contrast call drawFunc
After working/studying hours with canvas i have managed to get the image clone and it's pixels now i have made the user select a color from a color specterm and i have that color hex in my function :
move: function (color) {
// 'color' is the value user selected
var img_id = jQuery(".selected_bg_img").attr("id");
alert(img_id);
var x = 0;
var y = 0;
var width = 409;
var height = 409;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById(img_id);
ctx.drawImage(img,x,y,width,height);
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
alert(data);
}
now two tasks are getting in way,
1. How do we extract the maximum color from data ?
2. How do we convert that maximum color to the color we got in function ?
for live working example i have link given at end
NOTE: Select the images (any last 3) from left side of the product image and and when color is choose it clones the image to the canvas below.
Here i am trying to clone the image with replacement of maximum color with the color user selected.
NOTE: Maximum color i mean (dominant color in image), e.g http://lokeshdhakar.com/projects/color-thief/ this project is getting the dominant color of image but it's on node and i'm trying to get the dominant and to change that color before cloning too .
for (var i=0;i<imgData.data.length;i+=4)
{
imgData.data[i]=255-imgData.data[i];
imgData.data[i+1]=255-imgData.data[i+1];
imgData.data[i+2]=255-imgData.data[i+2];
imgData.data[i+3]=255;
}
*****EDIT*****
My problem is not very complex i think i have this image
so we can see clearly that the dominant color is grey, by any method i am just trying to replace that color with the new color i have in my function move and draw that image with the new color. The image from where i have taken and shows another example :
http://www.art.com/products/p14499522-sa-i3061806/pela-silverman-colorful-season-i.htm?sOrig=CAT&sOrigID=0&dimVals=729271&ui=573414C032AA44A693A641C8164EB595
on left side of image when we select the similar image they have option "change color" at the bottom center of image. This is what exactly i'm trying to do.
So now i tried to read the image 1x1 and this is what i get in the console when i log it(particular for the image i have shown) :
[166, 158, 152, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…]
So it maybe the very first start from top left corner, i guess it need to be iterated over whole image and this is what i get when i iterated over whole image:
[110, 118, 124, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255…]
The loop i used for iteration is:
var imageData = ctx.getImageData(0,0,width,height);
var data = imageData.data;
for (var i=0;i<data.length;i+=4)
{
data[i]=255-data[i];
data[i+1]=255-data[i+1];
data[i+2]=255-data[i+2];
data[i+3]=255;
}
console.log(data);
Is this iteration right ? If yes, it seems to be now matter of replacing the dominant color and i'm blank here how do we replace it and write back image with the replaced color or is there something more ?
*************EDIT***********
i have now user value in rgb, need to look for places where that value should be placed
This answer may be what you want as it is a little unclear.
Finding the dominant colour in an image
There are two ways that I use. There are many other ways to do it, which is the best is dependent on the needs and quality requiered. I will concentrat on using a histogram to filter out irrelevent pixels to get a result.
The easy way.
Create a canvas that is 1 by 1 pixel. Ensure that canvas smoothing is on.
ctx.imageSmoothingEnabled = true;
ctx.mozImageSmoothingEnabled = true;
The draw the image onto that 1 by 1 canvas
ctx.drawImage(image,0,0,1,1);
Get the pixel data
var data = ctx.getImageData(0,0,1,1);
And the rgb values are what you are after.
r = data.data[0];
g = data.data[0];
b = data.data[0];
The result applied to the image below.
The long way
This method is long and problematic. You need to ignore the low and high values in the histogram for rgb (ignore black and white values) and for HSL ignore Saturations and Values (Lightness) that are 0 or 100% or you will get reds always dominating for images that have good contrast.
In image processing a histogram is a plot of the distribution of image properties (eg red green blue) within the image. As digital images have discrete values the histogram (a bar graph) will plot along the x axis the value and in the y axis the number of pixels that have that value.
An example of the histogram. Note that this code will not run here as there is cross origin restriction. (sorry forgot my browser had that disabled).
/** CopyImage.js begin **/
// copies an image adding the 2d context
function copyImage(img){
var image = document.createElement("canvas");
image.width = img.width;
image.height = img.height;
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0);
return image;
}
function copyImageScale(img,scale){
var image = document.createElement("canvas");
image.width = Math.floor(img.width * scale);
image.height = Math.floor(img.height * scale);
image.ctx = image.getContext("2d");
image.ctx.drawImage(img, 0, 0,image.width,image.height);
return image;
}
/** CopyImage.js end **/
function getHistogram(img){ // create a histogram of rgb and Black and White
var R,G,B,BW;
R = [];
G = [];
B = [];
BW = []; // Black and white is just a mean of RGB
for(var i=0; i < 256; i++){
R[i] = 0;
G[i] = 0;
B[i] = 0;
BW[i] = 0;
}
var max = 0; // to normalise the values need max
var maxBW = 0; // Black and White will have much higher values so normalise seperatly
var data = img.ctx.getImageData(0,0,img.width,img.height);
var d = data.data;
var r,g,b;
i = 0;
while(i < d.length){
r = d[i++]; // get pixel rgb values
g = d[i++];
b = d[i++];
i++; // skip alpha
R[r] += 1; // count each value
G[g] += 1;
B[b] += 1;
BW[Math.floor((r+g+b)/3)] += 1;
}
// get max
for(i = 0; i < 256; i++){
max = Math.max(R[i],G[i],B[i],max);
maxBW = Math.max(BW[i],maxBW);
}
// return the data
return {
red : R,
green : G,
blue : B,
gray : BW,
rgbMax : max,
grayMax : maxBW,
};
}
function plotHistogram(data,ctx,sel){
var w = ctx.canvas.width;
var h = ctx.canvas.height;
ctx.clearRect(0,0,w,h); // clear any existing data
var d = data[sel];
if(sel !== "gray"){
ctx.fillStyle = sel;
}
var rw = 1 / d.length; // normalise bar width
rw *= w; // scale to draw area;
for(var i = 0; i < d.length; i++ ){
var v = 1-(d[i]/data.rgbMax); // normalise and invert for plot
v *= h; // scale to draw area;
var x = i/d.length; // normaise x axis
x *= w; // scale to draw area
if(sel === 'gray'){
ctx.fillStyle = "rgb("+i+","+i+","+i+")";
}
ctx.fillRect(x,v,rw,h-v); // plot the bar
}
}
var canMain = document.createElement("canvas");
canMain.width = 512;
canMain.height = 512;
canMain.ctx = canMain.getContext("2d");
document.body.appendChild(canMain);
var ctx = canMain.ctx;
var can = document.createElement("canvas");
can.width = 512;
can.height = 512;
can.ctx = can.getContext("2d");
// load image and display histogram
var image = new Image();
image.src = "http://i.stack.imgur.com/tjTTJ.jpg";
image.onload = function(){
image = copyImage(this);
var hist = getHistogram(image);
// make background black
ctx.fillStyle = "black"
ctx.fillRect(0,0,ctx.canvas.width,ctx.canvas.height);
// create and show each plot
plotHistogram(hist,can.ctx,"red");
document.body.appendChild(copyImageScale(can,0.5));
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"green");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"blue");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "lighter"
ctx.drawImage(can,0,0,canvas.width,canvas.height);
plotHistogram(hist,can.ctx,"gray");
document.body.appendChild(copyImageScale(can,0.5));
ctx.globalCompositeOperation = "source-over"
ctx.globalAlpha = 0.9;
ctx.drawImage(can,0,0,canvas.width,canvas.height);
ctx.globalAlpha = 1;
}
As the above code required a hosted image the results are shown below.
The image
The RGB and gray histograms as output from above code.
From this you can see the dominant channels and the distribution of rgb over the image (Please note that I removed the black as this image has a lot of black pixels that where make the rest of the pixel counts shrink into insignificance)
To find the dominant colour you can do the same but for the HSL values. For this you will need to convert from RGB to HSL. This answer has a function to do that. Then it is just a matter of counting each HSL value and creating a histogram.
The next image is a histogram in HSL of the above sample image.
As you can see there is a lot of red, then a peek at yellow, and another in green.
But as is this still will not get you what you want. The second histogram (saturation) shows a clear peak in the center. There are a lot of colours that have good saturation but this does not tell you what colour that is.
You need to filter the HSL value to around that peak.
What I do is multiply the HSL values by the f(s) = 1-Math.abs(s-50)/50 s is Saturation range 0-100. This will amplify hue and value where saturation is max. The resulting histogram looks like
Now the peak hue (ignoring the reds) is orange. The hue value is ~ 42. Then you apply a filter that removes all pixels that are not near the hue = 42 (you may want to give a falloff). You apply this filter on the HSL value you get after the last step. The next image shows the resulting image after applying this filter to the original
and then get a sum of all the remaining pixel's R,G,B. The mean of each RGB value is the common colour.
The common colour as by this method.
Note the result is different than if you apply this method as described and in the code above. I used my own image processing app to get the instrume steps and it uses true logarithmic photon counts for RGB values that will tend to be darker than linear interpolation. The final step expands the filtered pixel image to an instrume step that is too complicated to describe here (a modification on the easy method at start of answer). looks like
Also I applied this to the whole image, this can be very slow for large images, but it will work just as well if you first reduce the size of the image (must have image smoothing on (defaults of most browsers)). 128 8 128 is a good size but you can go down lower. It will depend on the image how small you can make it befor it fails.
I am attempting to fill a Canvas element with a single linear gradient between White and a Dynamic colour that will be determined at runtime.
To this effect, I have this function, that receives a floating point number as it's argument, and I am attempting to plug that variable into the alpha value of a RGBA colour.
function setCanvas(fraction) {
fraction = fraction.toFixed(2);
context.rect(0, 0, canvas.width, canvas.height);
var grad = context.createLinearGradient(0, 0, canvas.width, canvas.height);
grad.addColorStop(0, '#FFFFFF');
grad.addColorStop(1, 'rgba(255, 255, 255, fraction)'); // SYNTAX ERROR
context.fillStyle = grad;
context.fill();
}
This is the error message in the log:
Uncaught SyntaxError: Failed to execute 'addColorStop' on 'CanvasGradient': The value provided ('rgba(255, 255, 255, fraction)') could not be parsed as a color.
I can log the value of fraction and it is always normalized between 0.0 and 1.0, which is what the documentation says it needs... but if I statically type in the same value (0.76, for example) into my RGBA colour, then everything works swimmingly...
Am I missing something obvious? Why isn't this working ?
I think you meant to do this
grad.addColorStop(1, 'rgba(255, 255, 255, ' + fraction+ ')');
You're including the string fraction instead of the value.
I've been following the lessons about transparency and gradients on the Mozilla site: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors but I have not been able to figure this one out.
I know I can achieve these effects with a png image; however, in the program I am working on the gradient will change constantly according to where the image is moved.
Here's an example of the effect I'm looking for.
http://home.insightbb.com/~epyonxl1/gradientex.jpg
Its possible to use context.globalCompositeOperation to make the the mask
context.drawImage(img, 0, 0, img.width, img.height, 0,0, img.width, img.height);
context.globalCompositeOperation = "destination-out";
gradient = context.createLinearGradient(0, 0, 0, img.height);
gradient.addColorStop(0, "rgba(255, 255, 255, 0.5)");
gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
context.fillStyle = gradient;
context.fillRect(0, 0, img.width, img.height);
This do not do per pixel manipulation and should be faster
To correctly merge two images using a transparency mask it's first necessary to take one of the two images and put it into an off screen canvas, and add the desired transparency mask using context.globalCompositeOperation = destination-out per #Tommyka's answer
var offscreen = document.createElement('canvas'); // detached from DOM
var context = offscreen.getContext('2d');
context.drawImage(image1, 0, 0, image1.width, image1.height);
var gradient = context.createLinearGradient(0, 0, 0, img.height);
gradient.addColorStop(0, "rgba(255, 255, 255, 0.5)");
gradient.addColorStop(1, "rgba(255, 255, 255, 1.0)");
context.globalCompositeOperation = "destination-out";
context.fillStyle = gradient;
context.fillRect(0, 0, image1.width, image1.height);
Then, to actually merge the two images you then need to draw the other image into another canvas, and then simply draw the alpha-composited offscreen canvas on top of that:
var onscreen = document.getElementById('mycanvas');
var context2 = onscreen.getContext('2d');
context2.drawImage(image2, 0, 0, image2.width, image2.height);
context2.drawImage(offscreen, 0, 0, onscreen.width, onscreen.height);
Demo at http://jsfiddle.net/alnitak/rfdjoh31/4/
I've aded some code here: https://code.google.com/archive/p/canvasimagegradient/ that adds a drawImageGradient function to the CanvasRenderingContext2D. You can draw an image with a linear or radial gradient. It doesn't work in IE, even with excanvas, due to the lack of getImageData/putImageData support.
The following code for example will draw an image with a radial gradient (context retrieve and image load not shown):
var radGrad = ctx.createRadialGradient(
img.width / 2, img.height / 2, 10,
img.width / 2, img.height / 2, img.width/2);
radGrad.addColorStop(0, "transparent");
radGrad.addColorStop(1, "#000");
ctx.drawImageGradient(img, 112.5, 130, radGrad);
The code works as follows:
Create a canvas element dynamically and draw the image on it.
Retrieve the imageData for this new canvas.
Retrieve the imageData for the location on the canvas you want to draw the image on to.
Iterate through the destination imageData and update each pixel adding together a percentage (derived from the gradient transparency value) of the image and destination pixel values.
Finally put the updated image data back onto the destination canvas.
Obviously performance is an issue as images get larger. The image on https://code.google.com/archive/p/canvasimagegradient/ it takes about 6-10ms to draw. A 1024x768 image takes about 100ms-250ms to draw. Still usable though as long as you're not animating.
If you need to make an image transparent set the ctx.globalAlpha to whatever you need (1, no transparency, is default). Then reset it after you draw your image. This URL probably will help as well https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Compositing.
I have modernized Alnitak's response by incorporating asynchronous loading of the images.
I also got rid of magic numbers.
const imageUrls = [
// Base image
'http://www.netstate.com/states/symb/flowers/images/apple_blossoms.jpg',
// Gradient image
'http://www.netstate.com/states/symb/flowers/images/oklahoma_rose.jpg'
];
const main = async () => {
const ctx = document.getElementById('cv').getContext('2d'),
baseImg = await loadImage(imageUrls[0]),
gradImg = await loadImage(imageUrls[1]);
draw(ctx, baseImg, gradImg);
};
/**
* Loads an Image object via a Promise.
* #param {String} url - Location of an image file
* #return {Promise<Image>} Returns a promise that resolves to an Image.
*/
const loadImage = (url) => new Promise((resolve, reject) => {
const img = new Image();
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', reject);
img.src = url;
});
/**
* Draws an image, as a gradient applied to it, above another image.
* #param {Image} baseImg - Image that is applied under the gradient
* #param {Image} gradImg - Image to be applied as a gradient
*/
const draw = (ctx, baseImg, gradImg) => {
const {width, height} = baseImg,
originX = Math.floor(width / 2),
originY = Math.floor(height / 2),
radius = Math.min(originX, originY);
const offScreen = document.createElement('canvas');
offScreen.width = offScreen.height = width;
const ctx2 = offScreen.getContext('2d');
ctx2.drawImage(gradImg, 0, 0, width, height);
const gradient = ctx2.createRadialGradient(originX, originY, 0, originX, originY, radius);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 1)');
ctx2.fillStyle = gradient;
ctx2.globalCompositeOperation = 'destination-out';
ctx2.fillRect(0, 0, width, height);
ctx.drawImage(baseImg, 0, 0, width, height);
ctx.drawImage(offScreen, 0, 0, width, height);
};
main();
<canvas id="cv" width="300" height="300"></canvas>