首页 > 解决方案 > 如何使用 JavaScript 中的单击事件更改 HTML 画布中的线宽

问题描述

我想通过单击事件将画布中的线宽从 5 更改为 10,但它在 JavaScript 中不起作用

function draw(e) {
     if (!painting) {
         return;
     }

     exitdraw(e);
     c.lineWidth = 5;
     c.lineTo(e.clientX, e.clientY);
     c.lineCap = 'round';
     c.strokeStyle = 'aqua';
     c.stroke();
     c.beginPath();
     c.moveTo(e.clientX, e.clientY);
}

    //this is the listener i want to change the linewidth
    var canvas = document.querySelector('#canvas');
    var btn = document.getElementById('button');
    btn.addEventListener('click',function(){

        canvas.getContext('2d').lineWidth = 10;
    })

标签: javascripthtmlcss

解决方案


<button onclick="changeWidth()">Change Width</button>
<br />
<canvas height="150" id="canvas" width="200"></canvas>

<script>
    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");

    var lineWidth = 5;

    function draw() {
        ctx.beginPath();
        ctx.lineWidth = lineWidth;
        ctx.arc(100, 75, 32, 0, 2 * Math.PI);
        ctx.stroke();
    }

    draw();

    function changeWidth() {
        lineWidth = 10;
        draw();
    }
</script>


推荐阅读