所示代码演示如下功能:
- 在画布(canvas, z-index:3;)上描画某一个 下层的影像(img1, z-index:1;)的时候, 如文本框显示,可以知道图中任何一点,即鼠标所在的位置[x,y]。
- 以画箭头为例,先绘出曲线,如三次贝塞尔曲线、半圆弧等,再在终点搞定箭头。
- 画箭头,要调用方法 function arrow( g, x, y, d, delta) {...}。 其中参数:g 为画笔,x,y 是曲线终点的坐标,d 是根据线条的粗细,控制箭头大小的系数, 而 delta(单位: ° 度, 不是弧度)是顺时针转动的度数(°)。delta 的数值,视曲线终结时的"指向"而定。
- 图画的工作完成后,再删去所有辅助层面, 即html的辅助元素,仅保留你的作品图: canvas id="myCanvas"。
<html>
<head>
<meta charset="utf-8"/>
<title>CoordinateSheet</title>
<script>
function drawPicture(){
var g = document.getElementById("myCanvas").getContext("2d");
g.lineWidth="4";
g.strokeStyle="blue";
g.arc(600,100,80, Math.PI,0);
g.stroke();
arrow(g,680,100, 1, 0);
g.lineWidth="6";
g.beginPath();
g.moveTo(520,200);
g.bezierCurveTo(580,160,820,160,780,200);
g.stroke();
arrow(g, 780, 200, 1.5, 24);
g.lineWidth="10";
g.beginPath();
g.moveTo(520,300);
g.bezierCurveTo(600,250,700,440,780,300);
g.stroke();
arrow(g, 780, 300, 2,-150);
g.lineWidth="15";
g.beginPath();
g.moveTo(400,500);
g.bezierCurveTo(500,450,720,640,780,500);
g.stroke();
arrow(g, 780, 500, 3, -155);
}
document.onmousemove = getMouseXY;
function getMouseXY(e) {
tempX = event.clientX
tempY = event.clientY
document.Show.X.value = tempX
document.Show.Y.value = tempY
}
function draw(){
var g2d = document.getElementById("coordinate").getContext("2d");
for (var i=0;i<=90;i++){
g2d.beginPath();
g2d.moveTo(i*10, 0);
g2d.lineTo(i*10,600);
if (i%10==0) g2d.strokeStyle="red"; else g2d.strokeStyle="black";
g2d.stroke();
}
for (var i=0;i<=60;i++){
g2d.beginPath();
g2d.moveTo(0 ,i*10);
g2d.lineTo(900 ,i*10);
if (i%10==0) g2d.strokeStyle="red"; else g2d.strokeStyle="black";
g2d.stroke();
}
g2d.font="15px ARIAL";
g2d.fillStyle="green";
for (var i=1; i<=6; i++) {
g2d.fillText(i + "00",900,i*100+5);
}
for (var i=1; i<=8; i++) {
g2d.fillText(i + "00",i*100-12,610);
}
}
function arrow( g, x, y, d, delta) {
g.save();
g.fillStyle="blue";
g.translate(x,y);
g.rotate(delta*Math.PI/180);
g.beginPath();
g.moveTo( -5*d, -5*d);
g.lineTo( 5*d, -5*d);
g.lineTo( 0, 10*d);
g.closePath();
g.fill();
g.restore();
}
function preparation(){
draw();
drawPicture();
}
</script>
<style>
#myCanvas{
z-index:3;
position:absolute;
left:0px;
top:0px;
}
#coordinate{
z-index:4;
position:absolute;
left:0px;
top:0px;
}
#img1{
z-index:1;
position:absolute;
left:0px;
top:0px;
}
#show{
z-index:5;
position:absolute;
left:350px;
top:0px;
font: 20px ARIAL;
font-weight:bolder;
color:#00F;
}
input{
font: 20px Arial;
font-weight:bolder;
color:#F00;
}
</style>
</head>
<body onLoad="preparation()">
<canvas id="myCanvas" width="1000" height="700" >
<p>Your browserdoes not support the canvas element!</p>
</canvas>
<canvas id="coordinate" width="1000" height="700" ></canvas>
<img id="img1" src="http://pic136.nipic.com/file/20170726/25687095_112638664000_2.jpg" width="600">
<form id="show" name="Show">
X: <input type="text" name="X" value="0" size="4"><br>
Y: <input type="text" name="Y" value="0" size="4">
</form>
</body>
</html>