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;
functiondraw(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 Imageconst downloadBtn = document.querySelector('.btn--download');
const downloadLink = document.querySelector('#download_link');
const locale = newDate().toLocaleString();
const filename = `doodle${locale}.png`;
downloadBtn.addEventListener('click', downloadImage);
functiondownloadImage() {
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: 00.1rem0.5rem0.1remrgba(43, 12, 1, 0.1);
}
<buttonclass="btn--download">Download</button><canvasid="draw"width="640"height="640"></canvas><aid="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?"