Is it possible to make say, a zoomed in canvas where every 5x5 block is actually 1 pixel in the final image and how do you "paint" the pixel with a color stored in a variable onclick? Any code I've tested ends up being strokes, clicking does nothing for some reason.
Asked
Active
Viewed 1.3k times
4
-
Does this answer your question? [What's the best way to set a single pixel in an HTML5 canvas?](https://stackoverflow.com/questions/4899799/whats-the-best-way-to-set-a-single-pixel-in-an-html5-canvas) – handle Feb 11 '20 at 10:24
1 Answers
4
Something like this?
<canvas id="canvas" style="width:100px; height:100px" width="5" height="5"></canvas>
<script>
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
//Background
context.fillStyle = "#000";
context.fillRect(0, 0, canvas.width, canvas.height);
canvas.addEventListener("click", function(e) {
var x = Math.floor(e.x * canvas.width / parseInt(canvas.style.width));
var y = Math.floor(e.y * canvas.height / parseInt(canvas.style.height));
//Zoomed in red 'square'
context.fillStyle = "#F00";
context.fillRect(x, y, 1, 1);
}, true);
</script>
Edit: Added click functionality

PiTheNumber
- 22,828
- 17
- 107
- 180

Jeffrey Sweeney
- 5,986
- 5
- 24
- 32
-
-
-
@jmoon Don't know (actually I don't think you can), but you could just make a big canvas with a bigger width/height (as in, everything is in proportion), and draw squares that are 20x20. As to why id doesn't work, it could have something to do with how I'm getting mouse coordinates (MouseEvent.x). – Jeffrey Sweeney Mar 04 '12 at 22:14
-
The issue is that I need it to be an exact sized base64 png, and only look larger when editing – jmoon Mar 04 '12 at 22:18
-
1In moz and webkit, you can disable canvas smoothing with: `ctx.mozImageSmoothingEnabled = false; ctx.webkitImageSmoothingEnabled = false;` – forresto May 07 '13 at 19:30