2个canvas叠加运用(时钟例子)

本文介绍了一种使用双层Canvas来优化HTML5 Canvas时钟绘制的方法,通过将不变的背景元素与变化的手针分开渲染,显著减少了重绘带来的性能消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习canvas,http://corehtml5canvas.com/code-live/,主要的学习方式就是通过上面的一些例子来学习canvas的一些用法。但是我发现,这里的例子,只要canvas的内容有一点点变化(甚至是某个元素位置的变动),都会去清空整个canvas然后整个canvas重绘。例如下面时钟的例子 

http://corehtml5canvas.com/code-live/ch01/example-1.11/example.html

但是,对于这个时钟的功能来说,每一秒变化,改变的只是指针,刻度数字和圆圈都不需要改变,就因为指针的变化而去重绘整个canvas是不是耗费了性能呢。如果把指针变化这部分提出来成为一层,然后刻度不变的那一部分作为一层,2层叠加,上面一层背景透明,这样,能达到同样的效果,又能减少重绘的部分,相应的性能也能提高。抱着这种想法我试验了一下。代码如下:

<html>
<head>
    <title>Clock</title>
    <style>
        body {
            background: #dddddd;
        }

        #canvas1 {
            position: absolute;
            left: 0px;
            top: 0px;
            margin: 20px;
            background: #ffffff;
            border: thin solid #aaaaaa;
        }

        #canvas2 {
            position: absolute;
            left: 0px;
            top: 0px;
            margin: 20px;
            border: thin solid #aaaaaa;
        }
    </style>
</head>
<body>
<canvas id="canvas1" width="400" height="400">
    Canvas not supported
</canvas>
<canvas id="canvas2" width="400" height="400">
    Canvas not supported
</canvas>
<script src="MyTestClock.js"></script>
</body>

</
html>

 

MyTestClock.js部分代码:

/**

 * Created by jackyWHJ on 14-2-26.

 */

var canvas1 = document.getElementById('canvas1'),
    context1 = canvas1.getContext('2d'),
    canvas2 = document.getElementById('canvas2'),
    context2 = canvas2.getContext('2d'),
    FONT_HEIGHT = 15,
    MARGIN = 35,
    HAND_TRUNCATION = canvas1.width/25,
    HOUR_HAND_TRUNCATION = canvas1.width/10,
    NUMERAL_SPACING = 20,
    RADIUS = canvas1.width/2 - MARGIN,
    HAND_RADIUS = RADIUS + NUMERAL_SPACING;

// Functions.....................................................
function drawCircle() {
    context1.beginPath();
    context1.arc(canvas1.width/2, canvas1.height/2,
        RADIUS, 0, Math.PI*2, true);
    context1.stroke();
}

function drawNumerals() {
    var numerals = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ],
        angle = 0,
        numeralWidth = 0; 
    numerals.forEach(function(numeral) {
        angle = Math.PI/6 * (numeral-3);
        numeralWidth = context1.measureText(numeral).width;
        context1.fillText(numeral,
            canvas1.width/2  + Math.cos(angle)*(HAND_RADIUS) - numeralWidth/2,
            canvas1.height/2 + Math.sin(angle)*(HAND_RADIUS) + FONT_HEIGHT/3);
    });
}
 
function drawCenter() {
    context1.beginPath();
    context1.arc(canvas1.width/2, canvas1.height/2, 5, 0, Math.PI*2, true);
    context1.fill();
}

function drawHand(loc, isHour,color) {
    var angle = (Math.PI*2) * (loc/60) - Math.PI/2,
        handRadius = isHour ? RADIUS - HAND_TRUNCATION-HOUR_HAND_TRUNCATION
            : RADIUS - HAND_TRUNCATION;
    context2.beginPath();
    context2.strokeStyle = color;
    context2.moveTo(canvas2.width/2, canvas2.height/2);
    context2.lineTo(canvas2.width/2  + Math.cos(angle)*handRadius,
        canvas2.height/2 + Math.sin(angle)*handRadius);
    context2.stroke();
}

 

function drawHands() {
    context2.clearRect(0,0,canvas2.width,canvas2.height);
    var date = new Date,
        hour = date.getHours();
    hour = hour > 12 ? hour - 12 : hour;
    drawHand(hour*5 + (date.getMinutes()/60)*5, true, "#FF0000");
    drawHand(date.getMinutes(), false, "#00FF00");
    drawHand(date.getSeconds(), false, "#0000FF");
}

 

function drawClock() {
    drawCircle();
    drawCenter();
    drawNumerals();
}

// Initialization................................................
context1.font = FONT_HEIGHT + 'px Arial';
drawHands();
drawClock();
loop = setInterval(drawHands, 1000);

浏览器看了下,原来重绘需要2ms,现在是1ms。。。

 

 

 

转载于:https://www.cnblogs.com/jackyWHJ/p/3571259.html

One of HTML5,s most exciting features, Canvas provides a powerful 2D graphics API that lets you implement everything from word processors to video games. In Core HTML5 Canvas, best-selling author David Geary presents a code-fueled, no-nonsense deep dive into that API, covering everything you need to know to implement rich and consistent web applications that run on a wide variety of operating systems and devices. Succinctly and clearly written, this book examines dozens of real-world uses of the Canvas API, such as interactively drawing and manipulating shapes, saving and restoring the drawing surface to temporarily draw shapes and text, and implementing text controls. You,ll see how to keep your applications responsive with web workers when you filter images, how to implement smooth animations, and how to create layered, 3D scrolling backgrounds with parallax. In addition, you,ll see how to implement video games with extensive coverage of sprites, physics, collision detection, and the implementation of a game engine and an industrial-strength pinball game. The book concludes by showing you how to implement Canvas-based controls that you can use in any HTML5 application and how to use Canvas on mobile devices, including iOS5. This authoritative Canvas reference covers * The canvas element-using it with other HTML elements, handling events, printing a canvas, and using offscreen canvases* Shapes-drawing, dragging, erasing, and editing lines, arcs, circles, curves, and polygons; using shadows, gradients, and patterns* Text-drawing, positioning, setting font properties; building text controls* Images-drawing, scaling, clipping, processing, and animating* Animations-creating smooth, efficient, and portable animations* Sprites-implementing animated objects that have painters and behaviors* Physics-modeling physical systems (falling bodies, pendulums, and projectiles), and implementing tweening for nonlinear motion and animation* Collision detection-advanced techniques, clearly explained* Game development-all aspects of game development, such as time-based motion and high score support, implemented in a game engine* Custom controls-infrastructure for implementing custom controls; implementing progress bars, sliders, and an image panner* Mobile applications-fitting Canvas apps on a mobile screen, using media queries, handling touch events, and specifying iOS5 artifacts, such as app icons Throughout the book, Geary discusses high-quality, reusable code to help professional developers learn everything they really need to know, with no unnecessary verbiage. All of the book,s code and live demonstrations of key techniques are available at corehtml5canvas.com.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值