【发布时间】:2013-02-10 04:33:15
【问题描述】:
我正在尝试使用 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/ 有人知道答案吗?它适用于形状和文本..
【问题讨论】:
-
愿意帮助...任何代码?
标签: html html5-canvas globalcompositeoperation