Javascript-在屏幕上绘制像素不起作用

时间:2014-04-13 11:47:18

标签: javascript html canvas

我使用canvas的javascript有问题。 我必须在画布上画一个像素,但这不起作用。

这是我的javascript代码:

   function load(){    
        canvas.width=window.screen.width;
        canvas.height=window.screen.height;
    }

    var canvas = document.getElementById("myCanvas");
    var canvasWidth = canvas.width;
    var canvasHeight = canvas.height;
    var ctx = canvas.getContext("2d");
    var canvasData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);


    function drawPixel (x, y, r, g, b, a) {
        var index = (x + y * canvasWidth) * 4;

        canvasData.data[index + 0] = r;
        canvasData.data[index + 1] = g;
        canvasData.data[index + 2] = b;
        canvasData.data[index + 3] = a;
    }


    function updateCanvas() {
        ctx.putImageData(canvasData, 0, 0);
    }


  canvas.addEventListener('mousemove', function(evt) {   
   for(i=0;i<1000;i++){
    drawPixel(i, 200, 255, 0, 0, 255);
   }
   updateCanvas(); 
  }, false);

我希望当我移动鼠标指针时,屏幕上会出现这条线。

html代码的部分是:

<canvas id="myCanvas"></canvas>

1 个答案:

答案 0 :(得分:0)

试试这个: JSFIDDLE DEMO

<强> HTML

<div style="display: block; width: 500px; border: 1px #000 solid; height: 350px">

    <canvas id="paper" width="500" height="350" >
    </canvas>
</div>

<强> JAVASCRIPT:

var drawing = false;
var prev = {};
var globalBrushSize = 3, globalBrushColor="#0000FF";

var doc = $(document),
    win = $(window),
    canvas = $('#paper'),
    ctx = canvas[0].getContext('2d');

    canvas.on('mousedown',function(e){
        e.preventDefault();
        drawing = true;
        prev.x = e.pageX;
        prev.y = e.pageY;

    });

    doc.bind('mouseup mouseleave',function(){
        drawing = false;
    });


    doc.on('mousemove',function(e){
        // Draw a line for the current user's movement
        if(drawing){

            drawLine(prev.x, prev.y, e.pageX, e.pageY);

            prev.x = e.pageX;
            prev.y = e.pageY;
        }
    });


    function drawLine(fromx, fromy, tox, toy){
        ctx.beginPath();
        ctx.lineWidth = globalBrushSize;
        ctx.strokeStyle = globalBrushColor;
        ctx.moveTo(fromx, fromy);
        ctx.lineTo(tox, toy);
        ctx.stroke();
    }

<强>更新

如果您不想要mousedown事件,只想在鼠标移动时绘制,请尝试 DEMO