【问题标题】:Change linewidth on canvas using slider in javascript/jquery使用 javascript/jquery 中的滑块更改画布上的线宽
【发布时间】:2019-11-16 15:53:16
【问题描述】:

我希望有人可以提供帮助。我正在做一个绘图应用程序。我正在尝试 使用滑块调整画布上的线宽。如果一个用户 在滑块上选择 2 然后线宽应该很细, 40 将是 很粗的线。 提前谢谢了, 菲利普

这是我的 HTML

<div id="theLineWidthSection" style="float:right; margin-right:170px; 
margin-top:-42px; position:relative;z-index:9999; cursor:pointer; 
overflow:hidden;">
Size: <input type="range" id="theLineWidth" min="2" max="40" 
value="2" title="Line width"> 
</div>  

这是我的 Javascript

$('#theLineWidth').change(function () {
var canvas = document.getElementById('drawingCanvas');
var lineSize = document.getElementById('theLineWidth');
var mySize = lineSize.value;

lineSize.addEventListener('change', changeLineWidth);

function changeLineWidth(){
mySize = lineSize.value;
context.lineWidth = mySize;
context.lineWidth = lineSize.value;        
}    
});

当滑块改变时,线宽不会改变。

【问题讨论】:

    标签: javascript jquery html html5-canvas


    【解决方案1】:

    问题是您在应用线宽更改之前没有使用画布context。这应该可以解决它:

    var canvas = document.getElementById('drawingCanvas');
    var context = canvas.getContext("2d")
    var lineSize = document.getElementById('theLineWidth');
    var mySize = lineSize.value;
    
    $('#theLineWidth').change(function () {
    mySize = lineSize.value;
    context.lineWidth = mySize;      
    });
    

    另外,将变量从函数中取出。无需在每次触发 change 事件时重新定义它们。

    【讨论】:

      【解决方案2】:

      这是一个演示,我使用滑块更改画布上的线宽。 我使用的事件是input,当输入值改变时触发。

      希望对你有帮助。

      var canvas = document.getElementById('drawingCanvas');
      var context = canvas.getContext("2d");
      var mySize = 2;
      //draw something on the canvas
      draw();
      
      theLineWidth.addEventListener("input",function () {
      var mySize = theLineWidth.value;
      // change the line width
      context.lineWidth = mySize;
      
      draw();
      });
      
      
      // a function that is drawing something on the canvas
      function draw(){
      //first clear the context
        context.clearRect(0,0,canvas.width,canvas.height);
        // next draw 
        context.beginPath();
        context.moveTo(10,75);
        context.lineTo(290,75);
        context.stroke();
      }
      #theLineWidthSection {
        float: right;
        margin-right: 170px;
        /* margin-top: -42px;*/
        position: relative;
        z-index: 9999;
        cursor: pointer;
        outline:1px solid;
        /*overflow: hidden;*/
      }
      
      canvas{border:1px solid}
      <div>
      Size: <input type="range" id="theLineWidth" min="2" max="40" 
      value="2" title="Line width"> 
      </div> 
      <canvas id="drawingCanvas"></canvas>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-03
        • 2022-01-26
        相关资源
        最近更新 更多