javascript 用画布绘制单个像素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9559159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:03:00  来源:igfitidea点击:

Drawing a single pixel w/canvas

javascriptjqueryhtmlcanvas

提问by jmoon

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.

是否可以说,一个放大的画布,其中每个 5x5 块实际上是最终图像中的 1 个像素,你如何用存储在变量 onclick 中的颜色“绘制”像素?我测试过的任何代码最终都是笔画,由于某种原因点击什么都不做。

回答by Jeffrey Sweeney

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

编辑:添加点击功能

Demo: http://jsfiddle.net/Cmpde/

演示:http: //jsfiddle.net/Cmpde/