我试图修复Uncaught TypeError:无法读取null的属性'getContext'

时间:2019-04-26 13:27:31

标签: javascript

我正在尝试在本地运行javascript,但是遇到了问题。

未捕获的TypeError:无法读取null的属性'getContext'

这是我的代码。

<script type = 'text/javascript'>
    const canvas = document.querySelector('#draw');
    const ctx = canvas.getContext('2d');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    ctx.strokeStyle = '#BADA55';
    ctx.lineJoin = 'round';
    ctx.lineCap =  'round';
    ctx.lineWidth = 100;

    //let isDrowing = false;
    let lastX = 0;
    let lastY = 0;
    let hue = 0;
    let direction = true;

    function draw (e){
        if(!isDrowing) return;
        console.log(e);
        ctx.strokeStyle = 'hsl(${hue}, 100%, 50%)';
        ctx.beginPath();
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
        [lastX, lastY] = [e.offsetX, e.offsetY];
        hue++
        if(hue >= 360){
            hue =0;
        }
        if (ctx.lineWidth >= 500 ||ctx.lineWidt <=1){
            direction = !direction;
        }
        if(direction){
            ctx.lineWidth++;
        } else {
            ctx.lineWidth--;
        }
        canvas.addEventListener('mousedown',(e)=>{
            isDrowing =true;
            [lastX, lastY] = [e.offsetX, e.offsetY];
        });
        canvas.addEventListener('mousemove', draw);
        canvas.addEventListener('mouseup',()=> isDrawing=false);
        canvas.addEventListener('mouseout', () =>isDrowing=false);

    }
 </script>
</head> <body>
<canvas id="draw" width="800" height="800"></canvas>
 </body>

0 个答案:

没有答案