javascript - 使用单选按钮显示/隐藏 Canvas

标签 javascript html canvas

我是 Javascript 和 Canvas 的新手,我使用过很多资源,但现在我很困惑。我正在使用 Canvas 进行服装定制。 这是我的 HTML:

 //these are my button samples
<input type="radio" id="shape1" name="round" onchange="display()" /> 
<input type="radio" id="shape2" name="box" onchange="display()" />

// this is where I'll display the canvas
<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"> </canvas>

所以对于我的 Javascript 我有这个:

  function display() { 
    if (document.getElementById('shape1').checked) {
      var canvasC = document.getElementById('displaycanvas'),
          context = canvasC.getContext('2d');
           context.beginPath();
           context.arc(95,50,40,0,2*Math.PI);
           context.stroke();     }

    if (document.getElementById('shape2').checked) {
      var canvasR = document.getElementById('displaycanvas'),
          context = canvasR.getContext('2d');
            context.beginPath();
            context.rect(50, 27, 350, 400);    }
}

它们都工作正常,如果我选择这些按钮之一,它会显示形状。我关心的是如何一次仅显示 1 个形状

我不确定切换是否正确,请告诉我正确的做法是什么。预先非常感谢您,

最佳答案

您需要为 radio 指定相同的名称才能切换它们,并且还需要清除 Canvas 。

我现在对 Canvas 使用了相同的名称

window.onload = function() {
  document.querySelector("#shape1").onclick = document.querySelector("#shape2").onclick = function() {
    var canvas = document.querySelector('#displaycanvas');
    context = canvas.getContext('2d');
    context.clearRect(0,0,canvas.width,canvas.height);
    context.beginPath();
    if (this.id == "shape1") {
      context.arc(95, 50, 40, 0, 2 * Math.PI);
    } else {
      context.rect(50, 27, 350, 400);
    }
    context.stroke();
  }
}
<input type="radio" id="shape1" name="shape" value="round" />
<input type="radio" id="shape2" name="shape" value="box" />
<canvas id="displaycanvas" height="450px" width="820px" style="position:absolute;"></canvas>

如果你想要两 block Canvas ,你可以这样做

window.onload = function() {
  document.querySelector("#shape1").onclick = function() {
    document.querySelector('#displaycanvas1').style.display="";
    document.querySelector('#displaycanvas2').style.display="none";
  }
  document.querySelector("#shape2").onclick = function() {
    document.querySelector('#displaycanvas2').style.display="";
    document.querySelector('#displaycanvas1').style.display="none";
  }
}

仍然给 radio 提供相同的名称

关于javascript - 使用单选按钮显示/隐藏 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40609935/

相关文章:

Javascript 正则表达式 - 删除除分号外的所有特殊字符

javascript - JQuery 检查 localStorage 是否设置

html - 为什么 HTML 不在我下面的代码片段中采用 a、b、c 的值?

html - 使用鼠标在 HTML5 Canvas 上绘图

javascript - 触摸事件初始坐标

javascript - 我们如何对 Canvas 中使用的图案图像进行灰度化(javascript)

javascript - 如何正确使用拼接和切片

javascript - html多输入类型颜色,将选择的颜色插入数据库

javascript - HttpCompileException 未被用户代码处理(当我在脚本中添加 C# 代码时)

html - 右对齐 div 并防止容器折叠