簡體   English   中英

在同一頁面的多個畫布上使用canvas.getContext(“ 2d”)

[英]Using canvas.getContext(“2d”) on multiple canvases on same page

我正在嘗試制作一個頁面,允許用戶選擇他們要繪制的畫布大小。

為此,我創建了一個頁面,其中包含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個畫布? 完整的代碼以防萬一

你應該嘗試這樣的事情

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;
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM