我正在尝试使用 HTML 5 的 canvas 元素制作时钟。
我想要做的是每秒划一条线,然后擦除前一条线。
我想用绘制另一条线来擦除前一条线,globalCompositeOperation='xor';
但它不起作用!
这是代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Clock</title>
</head>
<body onload="spin()">
<canvas id="myCanvas" width="578" height="400"></canvas>
<script>
var firstTime = 0;
var prevX=null;
var prevY=null;
function spin() {
//get the canvas element
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
//get the right angle for the clock hand
var date = new Date;
var seconds = date.getSeconds();
var a = seconds*6;
var angleRadian = a*Math.PI/180;
var angle = 1/2*Math.PI - angleRadian;
if(a > 360)
a = 0;
//Erase the previous line, if it has been drawn.
if(prevX!=null)
erasePrevLine(angle, canvas, context);
//draw line
drawLine(angle, 100, canvas, context);
//repeat for the next second
setTimeout(spin, 500);
}
function drawLine(angle, radius, canvas, context) {
var centerX = canvas.width/2;
var centerY = canvas.height/2;
var xTarget = centerX + Math.cos(angle)*radius;
var yTarget = centerY - Math.sin(angle)*radius;
//save this state to be erased
prevX = xTarget;
prevY = yTarget;
//draw
context.beginPath();
context.moveTo(centerX,centerY);
context.lineTo(xTarget, yTarget);
context.stroke();
}
function erasePrevLine(angle, canvas, context) {
context.globalCompositeOperation = 'xor';
var centerX = canvas.width/2;
var centerY = canvas.height/2;
prevAngle = angle + (Math.PI/180*6);
var xTarget = prevX;
var yTarget = prevY;
//draw on the previous line
context.beginPath();
context.moveTo(centerX,centerY);
context.lineTo(xTarget, yTarget );
context.stroke();
}
</script>
</body>
</html>
这是现场示例: http: //jsfiddle.net/pyerT/1/ 有人知道答案吗?它适用于形状和文本..