首页 > 代码库 > canvas

canvas

canvas实现简易画布

function Canvas(Obj,Can,Color,fn){ //参数二代表canvas对象,参数三代表2d对象,参数四代表颜色
  EventUtil.addHandler(Obj,"touchstart",function(evt){
    Can.save()
    fn&&fn()
    Can.beginPath();
    Can.lineWidth=9;
    Can.strokeStyle=Color;
    var touch=evt.touches[0];
    var x=touch.pageX-Obj.offsetLeft;
    var y=touch.pageY-Obj.offsetTop;
    Can.moveTo(x,y);
  });
  EventUtil.addHandler(Obj,"touchmove",function(evt){
    var touch=evt.touches[0];
    var disX=touch.pageX;
    var disY=touch.pageY;
    if(evt.cancelable) {
      if(!evt.defaultPrevented) {
        evt.preventDefault();
      }
    }

    var touch=event.touches[0];
    var x=touch.pageX-Obj.offsetLeft;
    var y=touch.pageY-Obj.offsetTop;
    Can.lineTo(x,y);
    Can.stroke();
  });
  EventUtil.addHandler(Obj,"touchend",function(evt){
    Can.closePath();
    Can.restore()
    if(evt.cancelable){
      if(!evt.defaultPrevented){
        evt.preventDefault();
      }
    }
  })
}

canvas转化图片

<html>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=device-width,user-scalable=no"/>
<head>
<script>
  window.onload = function() {
    draw();
    var saveButton = document.getElementById("saveImageBtn");
      bindButtonEvent(saveButton, "click", saveImageInfo);
  };
  function draw(){
    var canvas = document.getElementById("thecanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgba(125, 46, 138, 0.5)";
    ctx.fillRect(25,25,100,100);
    ctx.fillStyle = "rgba( 0, 146, 38, 0.5)";
    ctx.fillRect(58, 74, 125, 100);
    ctx.fillStyle = "rgba( 0, 0, 0, 1)"; // black color
    ctx.fillText("Gloomyfish - Demo", 50, 50);
  }

  function bindButtonEvent(element, type, handler) {
    if(element.addEventListener) {
      element.addEventListener(type, handler, false);
    } else {
      element.attachEvent(‘on‘+type, handler);
  }
}

  function saveImageInfo (){
    var mycanvas = document.getElementById("thecanvas");
    var image = mycanvas.toDataURL("image/png");
    var w=window.open(‘about:blank‘,‘image from canvas‘);
    var div=document.createElement(‘div‘);
    w.appendChild(div);
    //w.document.write("<img src=http://www.mamicode.com/‘"+image+"‘ alt=‘from canvas‘/>");
  }
</script>
</head>
<body bgcolor="#E6E6FA">
<div>
  <canvas width=200 height=200 id="thecanvas"></canvas>
  <button id="saveImageBtn">Save Image</button>
</div>
</body>
</html>

 

canvas