在画布上制作不同的数字html5

时间:2015-05-13 19:30:30

标签: javascript jquery html5 canvas

我有画布,但我不知道如何在覆盖它的同一画布上创建其他图形,我有2个按钮,一个用于放置图像然后链接它并制作一个图形而另一个用于放置另一个图形图像,但在不同的数字。 例如,你有按钮" a"和按钮" b"。按钮" a"放置图像并使图形链接图像。现在你要开始一个新的数字,你使用按钮" b",放一个图像,当你回到按钮" a"它必须链接新图像按钮" b"已放在前面。我不知道如果我解释得好。 如果您使用一个按钮或另一个按钮使用相同的功能进行绘制,我将尝试传递变量进行比较。变量为nFif nF=0 =>按钮" a" if nF=1 =>按钮" b"

这是我的代码

    function position(year, mon) { //that function puts the images in the html
    $('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');

}

    function draw(nF) {
    var fN = nF;
    var table = document.getElementById("table");
    var images = table.getElementsByTagName("img");
    var canvas = document.getElementById("miCanvas");
    var ctx = canvas.getContext("2d");
    var x, y; // Remember coordinates

    canvas.width = table.offsetWidth;
    canvas.height = table.offsetHeight;

    function connect(image, index) { //this function link the images
        var tabBcr = table.getBoundingClientRect();
        var imgBcr = image.getBoundingClientRect();
        x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
        y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;

        index === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
        ctx.save(); //save the state I think
    }
    // new path here
    ctx.beginPath();

    for (var i = 0; i < images.length; i++) {
        connect(images[i], i); // provide index so we can sep. move/line
    }
 if (fN == 1) {//This doesn't work :(
        ctx.fillStyle = "orange";
        ctx.globalCompositeOperation = "source-over";
        ctx.fill();
        cxt.restore();

    } else {
        // then at the end:
        ctx.fill();
        cxt.restore();

    }

}

This is one figure, you add the circles using "add person"

when you use "add new family", there should be two figures but there are mixed

1 个答案:

答案 0 :(得分:2)

由于您问题中的原始描述与新添加的图片有很大差异,因此我将此代码作为学习起点提供,不作任何解释:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

ctx.lineWidth=2;
var colors=['green','blue','gold','cyan'];

var figures=[];
var selectedFigure=-1;
var circles=[];
var selectedCircle=-1;
var connectors=[];

addFigure();

$('#new').attr('disabled',true);

$("#canvas").mousedown(function(e){handleMouseDown(e);});

$('#new').click(function(){
  addFigure();
});


///// functions

function addFigure(){
  figures.push({
    circleCount:0,
    color:randomColor(),
    lastCX:0,
    lastCY:0
  });
  selectedFigure=figures.length-1;
}

function addCircle(mx,my){

  var figure=figures[selectedFigure];

  var circle={
    id:circles.length,
    cx:mx,
    cy:my,
    radius:15,
    figure:selectedFigure,
    color:figure.color,
  };
  circles.push(circle);

  if(figure.circleCount>0){
    var connector={
      figure:selectedFigure,
      x0:figure.lastCX,
      y0:figure.lastCY,
      x1:mx,
      y1:my,
    }
    connectors.push(connector);
  }
  figure.lastCX=mx;
  figure.lastCY=my;
  figure.circleCount++;

  selectedCircle=circle.id;

  $('#new').attr('disabled',false);
}

function drawAll(){
  ctx.clearRect(0,0,cw,ch);
  for(var i=0;i<connectors.length;i++){
    drawConnector(connectors[i]);
  }
  for(var i=0;i<circles.length;i++){
    drawCircle(circles[i]);
  }
}

function drawCircle(circle){
  var highlighted=(circle.figure==selectedFigure);
  ctx.strokeStyle=(highlighted)?'red':'black';
  ctx.lineWidth=(circle.id==selectedCircle)?6:2;
  ctx.beginPath();
  ctx.arc(circle.cx,circle.cy,circle.radius,0,Math.PI*2);
  ctx.closePath();
  ctx.fillStyle=circle.color;
  ctx.fill();
  ctx.stroke();
  ctx.lineWidth=2;
}

function drawConnector(connector){
  var highlighted=(connector.figure==selectedFigure);
  ctx.strokeStyle=(highlighted)?'red':'lightgray';
  ctx.beginPath();
  ctx.moveTo(connector.x0,connector.y0);
  ctx.lineTo(connector.x1,connector.y1);
  ctx.stroke();
}


function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  if(selectedFigure<0){return;}

  var mouseX=parseInt(e.clientX-offsetX);
  var mouseY=parseInt(e.clientY-offsetY);

  var wasCircleClicked=false;;
  for(var i=0;i<circles.length;i++){
    var c=circles[i];
    var dx=mouseX-c.cx;
    var dy=mouseY-c.cy;
    if(dx*dx+dy*dy<=c.radius*c.radius){
      selectedFigure=c.figure;
      selectedCircle=i;
      var figure=figures[selectedFigure];
      figure.lastCX=c.cx;
      figure.lastCY=c.cy;
      wasCircleClicked=true;
      break;
    }                
  }

  if(!wasCircleClicked){
    addCircle(mouseX,mouseY);
  }

  drawAll();

}

function randomColor(){
  if(colors.length>0){
    var color=colors[0];
    colors.splice(0,1);
    return(color);
  }else{
    return('#'+Math.floor(Math.random()*16777215).toString(16));
  }
}
body{ background-color: white; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click on empty area to add a circle to the currently selected figure.<br><br>Click on a circle to select its figure.<br>Selected figures have a red stroke.<br>New circles will be connected to the last-clicked circle.</h4>
<button id=new>Add new figure</button><br>
<canvas id="canvas" width=400 height=300></canvas>

这是一个展示不同家庭成员的框架。

enter image description here enter image description here

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;        
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }

// vars
var selectedFamily=0;
var nextFamily=0;
var families=[];

// set listeners

$("#canvas").mousedown(function(e){handleMouseDown(e);});

$(document).on('change','.fam',function(){
  selectedFamily=this.value;
  $('#focusFamily').text('Click canvas to add person to family#'+selectedFamily);
  draw();
});

$('#addfamily').click(function(){ addFamily(); });

// add a first family
addFamily();

// functions

function addFamily(){
  families.push({id:nextFamily,people:[]});

  var id=nextFamily;

  var input=$('<input type=radio />');
  input.prop({
    'value':nextFamily,
    'id':'fam'+nextFamily,
    'name':'fams',
    'class':'fam',
    'checked':'checked',
  });
  var label=$('<label>',{
    'for':'fam'+nextFamily,
    'html':'Work on Family#'+nextFamily,
  });
  $('#family').append('<br>').append(input).append(label);

  selectedFamily=nextFamily;

  nextFamily++;

  draw();

}

function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mx=parseInt(e.clientX-offsetX);
  my=parseInt(e.clientY-offsetY);

  families[selectedFamily].people.push({x:mx,y:my});

  draw();
}

function draw(){
  ctx.clearRect(0,0,cw,ch);
  var people=families[selectedFamily].people;
  for(var i=0;i<people.length;i++){
    var person=people[i];
    ctx.beginPath();
    ctx.arc(person.x,person.y,15,0,Math.PI*2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke()
  }
}
body{ background-color: ivory; }
#container{
  display:inline-block;
  vertical-align:top;
  border:1px solid blue;
  padding:10px;
}
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<br>
<h4 id=focusFamily>Click canvas to add person to family#0</h4>
<canvas id="canvas" width=300 height=300></canvas>
<div id=container>
  <button id=addfamily>Add Family</button>
  <div id=family></div>
</div>