4
Let’s say I have a code that looks like this:
<html>
<head>
<style>
.centralizado {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<div>
<canvas class="centralizado" id="canvas">your browser is nope!</canvas>
</div>
<script>
function init() {
var ctx = document.getElementById("canvas").getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var pinta = false;
var red = green = blue = 127;
var rf = 1, gf = 1, bf = 1;
var rm = getAleatorio();
var gm = getAleatorio();
var bm = getAleatorio();
function desenha(e) {
var pos = getPosMouse(canvas, e);
posx = pos.x;
posy = pos.y;
if (pinta) {
ctx.fillStyle = "rgb(" + red + ", " + green + ", " + blue + ")";
ctx.fillRect(posx-4, posy-4, 8, 8);
}
}
canvas.onmousemove = function(e) {
desenha(e);
red += rm * rf;
green += gm * gf;
blue += bm * bf;
if (red >= 255 || red <= 0) { rf *= -1; rm = getAleatorio();}
if (green >= 255 || green <= 0) { gf *= -1; gm = getAleatorio();}
if (blue >= 255 || blue <= 0) { bf *= -1; bm = getAleatorio();}
};
document.getElementById("canvas").onmousedown = function() {
pinta = true;
};
document.getElementById("canvas").onmouseup = function() {
pinta = false;
}
function getPosMouse(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function getAleatorio() {
return Math.floor((Math.random() * 5) + 1);
}
}
</script>
<body onLoad="init();">
</html>
And once made available on my server, a visitor uses it to make a masterpiece like this:
How do I allow the user to save the drawing he does, not locally, but on my server?
when saving png it comes with transparent background. know how to tell me how to save with white background? I changed it to jpg and it was not.
– Glenys Mitchell