繁体   English   中英

使用javascript / jquery中的滑块更改画布上的线宽

[英]Change linewidth on canvas using slider in javascript/jquery

我希望有人能提供帮助。 我正在做一个绘图应用程序。 我正在使用滑块调整画布上的线宽。 如果用户在滑块上选择2,则线宽应较细,而40将是非常粗的线。 在此先感谢Filipe

这是我的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;        
}    
});

更改滑块后,线宽不会改变。

问题是您没有在应用线宽更改之前获取画布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事件触发时,都无需重新定义它们。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM