首页 > 解决方案 > 使用 javascript/jquery 中的滑块更改画布上的线宽

问题描述

我希望有人能帮忙。我正在做一个绘图应用程序。我正在使用滑块调整画布上的线宽。如果用户在滑块上选择 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;        
}    
});

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

标签: javascriptjqueryhtmlhtml5-canvas

解决方案


这是一个演示,我使用滑块更改画布上的线宽。我正在使用的事件是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>


推荐阅读