Erasing previously drawn lines on an HTML5 canvas

后端 未结 5 1687
臣服心动
臣服心动 2020-12-03 07:36

To play around with HTML5 canvas, I decided to make an app which draws an analogue clockface. Everything\'s fine, except that old lines don\'t get erased in the way that I w

5条回答
  •  没有蜡笔的小新
    2020-12-03 07:57

    Instead of erasing the things you don't want you can:

    1. save the state of the canvas
    2. draw the things you don't want
    3. restore the canvas to the saved state to 'erase' them

    This can be accomplished pretty easily using ImageData:

    var canvas = document.querySelector('canvas'),
        context = canvas.getContext('2d');
    
    context.fillStyle = 'blue';
    context.fillRect(0,0,200,200);
    
    // save the state of  the canvas here
    var imageData = context.getImageData(0,0,canvas.width,canvas.height);
    
    // draw a red rectangle that we'll get rid of in a second
    context.fillStyle = 'red';
    context.fillRect(50,50,100,100);
    
    setTimeout(function () {
        // return the canvas to the state right after we drew the blue rect
        context.putImageData(imageData, 0, 0);
    }, 1000);

提交回复
热议问题