使用滑块值调整画布元素中的矩形大小

时间:2016-03-31 18:43:42

标签: javascript html5 canvas slider drawrect

我希望能够使用滑块在画布上调整矩形大小,同时将这些值显示在两个文本框中。我有这个代码工作,但它保持旧值在画布上可见。我在致电import json import requests payload = { "assoc_term_in":"201535", "CRN_IN":"34688", "start_date_in":"03%2F28%2F2016", "end_date_in":"06%2F11%2F2016", "SUBJ":"ECEC", "CRSE":"451", "SEC":"001", "LEVL":"Undergraduate+Quarter", "CRED":"++++3.000", "GMOD":"Standard+Letter", "TITLE":"Computer+Arithmetic", "MESG":"DUMMY", "RSTS_IN":"" } r = requests.post("https://school.edu/pls/duprod/bwckcoms.P_Regs", data=json.dumps(payload)) print(r.text) 之前尝试使用clearRect(),但这阻止了我的滑块工作。

简而言之,我想在画布上绘制一个矩形,然后让两个滑块调整大小,一个用于宽度,一个用于高度。我对编码比较陌生,所以我知道我可能犯了一个明显的错误!

这是我的JS代码,用于将值打印到文本框并绘制矩形:

strokeRect()

我的HTML代码:

$(function() {
   var c1=document.getElementById("c1");
   var ctx1=c2.getContext("2d");
   $( "#slider1" ).slider({
  value:100,
  min: 10,
  max: 500,
  step: 10,
  slide: function( event, ui ) {
    $( "#textBox1" ).val(ui.value + "cm");
    ctx1.strokeRect(0, 0,$( "#slider1" ).slider( "value" ), $( "#slider2").slider( "value" ) );
  }
  });
  $( "#slider2" ).slider({
  value:100,
  min: 10,
  max: 500,
  step: 10,
  slide: function( event, ui ) {
    $( "#textBox2" ).val(ui.value + "cm");
    ctx1.strokeRect(0, 0,$( "#slider1" ).slider( "value" ), $( "#slider2").slider("value"));
  }
  });
$( "#textBox1" ).val($( "#slider1" ).slider( "value" ) + "cm");
$( "#textBox2" ).val($( "#slider2" ).slider( "value" ) + "cm");
 });

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些问题:

  • 您错过了"100cm"的结束语。
  • frameCanvas
  • 没有var c2=document.getElementById("frameCanvas")元素

可能会有更多故障 - 我在找到这些故障后停止了寻找。

或者,您可以在原始change元素上收听input-type=range个事件:



var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.fillStyle='skyblue';
ctx.strokeStyle='gray';
ctx.lineWidth=3;

var width=75;
var height=60;

// listen to slider events
$rwidth=$('#rwidth');
$rwidth.attr({min:20,max:150}).val(width);
$rwidth.on('input change',function(){
    width=parseInt($(this).val());
    draw();
});
//
$rheight=$('#rheight');
$rheight.attr({min:20,max:150}).val(height);
$rheight.on('input change',function(){
    height=parseInt($(this).val());
    draw();
});

draw();

function draw(){
    ctx.clearRect(0,0,cw,ch);
    ctx.fillRect(20,20,width,height);
    ctx.strokeRect(20,20,width,height);
}

body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Width:&nbsp<input id=rwidth type=range><br>
Height:&nbsp<input id=rheight type=range><br>
<br>
<canvas id="canvas" width=300 height=300></canvas>
&#13;
&#13;
&#13;