How Can I Make Background Color Of Downloaded Canvas Image White In JavaScript?
What I want to do I want to know how to make background color white. I built a drawing app with canvas. You can draw on the canvas by moving mouse while holding down the left click
Solution 1:
Like I mention on my previous answer, I found what is causing this issue with your code.
After adding:
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
What is making conflict with your code is this particular line:
ctx.globalCompositeOperation = 'hue';
What this does is it preserves the luma and chroma of the bottom layer, while adopting the hue of the top layer.
As I see your code, the thing is that you don't really need to use this kind of layering since you will only draw lines. So, try to removing it or replacing it with another layering type that can be found here.
See it working here:
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
let isDrawing = false;
let lastX = 0;
let lastY = 0;
function draw(e) {
if (!isDrawing) return; // Stop the fn from running when they are not moused down.
console.log(e);
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
// Save as Image
const downloadBtn = document.querySelector('.btn--download');
const downloadLink = document.querySelector('#download_link');
const locale = new Date().toLocaleString();
const filename = `doodle${locale}.png`;
downloadBtn.addEventListener('click', downloadImage);
function downloadImage() {
if (canvas.msToBlob) {
const blob = canvas.msToBlob();
window.navigator.msSaveBlob(blob, filename);
} else {
downloadLink.href = canvas.toDataURL('image/png');
downloadLink.download = filename;
downloadLink.click();
}
}
#draw {
display: block;
margin: 0 auto;
background: #fff;
border-radius: 0.3em;
box-shadow: 0 0.1rem 0.5rem 0.1rem rgba(43, 12, 1, 0.1);
}
<button class="btn--download">Download</button>
<canvas id="draw" width="640" height="640"></canvas>
<a id="download_link"></a>
Solution 2:
Remove this line
ctx.globalCompositeOperation = 'hue';
This is what makes your strokes white on a white background.
Post a Comment for "How Can I Make Background Color Of Downloaded Canvas Image White In JavaScript?"