<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>劃線</title>
<script language="javascript" type="text/javascript">
var c=document.getElementById("myCanvas");
var can=c.getContext("2d");
can.strokeStyle="rgb(0,182,0)";
var pois=new Array();
can.lineWidth=2;
mycanvas.onmousedown=function(e){
can.clearRect(0,0,500,500);
e=window.event||e;
var sX=e.pageX-this.offsetLeft;
var sY=e.pageY-this.offsetTop;
var poi=Object.create({x:sX,y:sY});
pois.push(poi);
if(pois.length==1)
{
can.beginPath();
}
if(pois.length>1)
{
can.moveTo(pois[0].x,pois[0].y);
for(var i=1;i<pois.length;i++)
{
can.lineTo(pois[i].x,pois[i].y);
}
can.stroke();
}
}
你canvas對象都沒放。。代碼沒有問題,除了mycanvas.onmousedown=function(e){....} 不能直接用id訪問,改為c變量
<canvas id="myCanvas"></canvas>
<script language="javascript" type="text/javascript">
var c=document.getElementById("myCanvas");
var can=c.getContext("2d");
can.strokeStyle="rgb(0,182,0)";
var pois=new Array();
can.lineWidth=2;
c.onmousedown=function(e){
can.clearRect(0,0,500,500);
e=window.event||e;
var sX=e.pageX-this.offsetLeft;
var sY=e.pageY-this.offsetTop;
var poi=Object.create({x:sX,y:sY});
pois.push(poi);
if(pois.length==1)
{
can.beginPath();
}
if(pois.length>1)
{
can.moveTo(pois[0].x,pois[0].y);
for(var i=1;i<pois.length;i++)
{
can.lineTo(pois[i].x,pois[i].y);
}
can.stroke();
}
}
</script>