HTML 5 - 画布(canvas)之画布平移操作实例

Html5画布操作之平移 | translate()

DOCTYPE HTML>
<html>
<head>
<title>平移title>
head>
<body>
<canvas id="canvas" width="400" height="400" style="background-color: rgb(222, 222, 222)">
您的浏览器不支持 canvas 标签
canvas>
<br />
<button type="button" onclick="drawIt();">不断地点我看 Demobutton>
<button type="button" onclick="clearIt();">清除画布button>

<script type="text/javascript">

var ctx = document.getElementById('canvas').getContext('2d');

var canvasX = 0;
var canvasY = 0;

var stepX = 20;
var stepY = 20;

function drawIt() {
if (canvasX == 0 && canvasY == 0)
ctx.strokeRect(
0, 0, 100, 100);

canvasX
= stepX;
canvasY
= stepY;

/*
* context.translate(x, y) - 将当前的用户坐标系平移指定的距离
* x - x 轴方向上需要平移的像素数
* y - y 轴方向上需要平移的像素数
*/
ctx.strokeStyle
= "blue";
ctx.translate(stepX, stepY);
ctx.strokeRect(
0, 0, 100, 100);
}

function clearIt() {
ctx.translate(
-canvasX, -canvasY);
canvasX
= 0;
canvasY
= 0;
ctx.strokeStyle
= "black";

ctx.clearRect(
0, 0, 400, 400);
}

script>
body>
html>

你可能感兴趣的:(前端)