So I'm trying to recreate a rainbow scratch paper effect. It works in two layers: a sheet of rainbow paper, with a black coating on top. I think the easiest thing to do would be to create two canvases – one black, layered on top of one rainbow. Is there a simpler approach? I am having a couple issues:
- my black canvas
can
isn't showing up! - for my rainbow canvas
can2
, I made found a gradient maker here, but am unsure how to make it fill the entire page.
Here's the code:
<style>
body{ margin: 0; } canvas {position: absolute;}
</style>
<body>
<canvas id ="can"></canvas>
<canvas id ="can2"></canvas>
<script>
var can = document.getElementsByTagName('canvas')[0];
can.width = window.innerWidth;
can.height = window.innerHeight;
var ctx = can.getContext('2d');
var fillBlack = can.getElementById("can");
fillBlack.style.color = "black";
var can2 = document.getElementsByTagName('canvas')[1];
can2.width = window.innerWidth;
can2.height = window.innerHeight;
var ctx2 = can2.getContext('2d');
colorScratch(.1, .2, .3, 0, 0, 0, 128, 127, 50);
var canBox = can.getBoundingClientRect();
ctx.clearRect(0, 0, can.width, can.height);
function colorScratch(freq1, freq2, freq3, phase1, phase2, phase3, center, width, len) {
for (var x = 0; x < len; x++){
for (var y = 0; y < width; y++){
var red = Math.sin(freq1 * x + phase1) * y + center);
var grn = Math.sin(freq2 * x + phase2) * y + center);
var blu = Math.sin(freq3 * x + phase3) * y + center);
ctx2.fill( '<div color="' + RGB2Color(red,grn,blu) + '">█</div>');
}
}
}
var stamp_shape = function(color, pos, size) {
ctx.beginPath();
ctx.arc(pos[0], pos[1], size, 0, 2*Math.PI);
ctx.fillStyle = color;
};
var stamp = function(x, y, size) {
var center = size / 2;
ctx.save();
ctx.globalAlpha = 0.6;
var grd = ctx.createRadialGradient(x, y, size, x, y, 0);
grd.addColorStop(1, 'rgba(255, 200, 200, 0.2)');
grd.addColorStop(0, 'rgba(255, 255, 255, 0)');
stamp_shape(grd, [x-center, y-center], size);
ctx.restore();
};
function getCoords(event) {
return {
x: event.pageX - canBox.left,
y: event.pageY - canBox.top
};
}
var drawing = false;
can2.onmousedown = function() {
drawing = true;
}
can2.onmouseup = function() {
drawing = false;
}
can2.onmousemove = function(e) {
var mousePos = getCoords(e);
if (!drawing) {
drawCursor(mousePos.x, mousePos.y, 50);
console.log(mousePos);
return;
}
clearCursor();
stamp(mousePos.x, mousePos.y, 50);
}
function drawCursor(x, y, size) {
ctx2.clearRect(0, 0, ctx2.canvas.width, ctx2.canvas.height);
ctx2.strokeStyle = '#F66';
ctx2.strokeRect(x - size / 2, y - size / 2, size, size);
}
function clearCursor() {
ctx2.clearRect(0, 0, ctx2.canvas.width, ctx2.canvas.height);
}
</script>
</body>
Thank you so much to anyone who can take a look!! xx