【问题标题】:Using canvas.getContext("2d") on multiple canvases on same page在同一页面上的多个画布上使用 canvas.getContext("2d")
【发布时间】:2016-06-01 21:11:10
【问题描述】:

我正在尝试制作一个允许用户选择他们想要绘制的画布大小的页面。

为此,我创建了一个页面,其中包含 3 个不同大小的画布,每个画布都有一个按钮。我在 CSS 中隐藏了所有画布,然后在单击相关按钮时使用 jQuery 显示画布。问题是,这破坏了在所有画布上实际绘制的能力,除了我的 HTML 文档中的第一个画布。我怀疑问题出在这段代码上:

HTML

<canvas width="400" height="250" class="small"></canvas>
<canvas width="600" height="400" class="medium"></canvas>
<canvas width="1000" height="800" class="large"></canvas>

JS

var context = $canvas[0].getContext("2d");

$canvas.mousedown(function(e){
  lastEvent = e;
  mouseDown = true;
}).mousemove(function(e){
   //Draw lines
  if(mouseDown) {
    context.beginPath();
    context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
    context.lineTo(e.offsetX, e.offsetY);
    context.strokeStyle = color;
    context.stroke();
    lastEvent = e;
  }
}).mouseup(function(){
  mouseDown = false;
}).mouseleave(function(){
  $canvas.mouseup(); 
});

有没有办法使用 .getContext 字符串选择调用 3 个画布? Full code in case it's useful

【问题讨论】:

  • 你想要一个上下文用于多个画布?
  • 您应该只需要一个画布使用选项设置其大小。可以通过记录点来复制图纸。通过使用 3 倍画布,您会消耗比所需更多的内存,并且绘图速度会慢 3 倍左右。

标签: javascript jquery html canvas


【解决方案1】:

你应该尝试类似的方法

var tab = [$canvas[0].getContext("2d"), $canvas[1].getContext("2d"), $canvas[2].getContext("2d")]
var lastEvent = null;
var mouseDown = false;

canvasParent.mousedown(function(e)
{
  lastEvent = e;
  mouseDown = true;
}).mousemove(function(e)
{
  if(mouseDown) {
    var i = 0;
    while (tab[i])
    {
      tab[i].beginPath();
      tab[i].moveTo(lastEvent.offsetX, lastEvent.offsetY);
      tab[i].lineTo(e.offsetX, e.offsetY);
      tab[i].strokeStyle = color;
      tab[i].stroke();
      i += 1;
    }
      lastEvent = e;
  }
}).mouseup(function(e)
{
  mouseDown = false;
}).mouseleave(function()
{
  var i = 0;
  while (tab[i])
  {
    tab[i].mouseup()
    i += 1;
  }
});

【讨论】:

    猜你喜欢
    • 2018-05-01
    • 2019-04-05
    • 2020-03-30
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多